package com.huashi.dealer.modular.business.order.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huashi.dealer.commonEntity.*;
import com.huashi.dealer.core.component.DataScopeInfo;
import com.huashi.dealer.core.exception.CommonException;
import com.huashi.dealer.commonEntity.Region;
import com.huashi.dealer.core.exception.ServiceException;
import com.huashi.dealer.core.util.BizAssertUtil;
import com.huashi.dealer.core.util.TimeUtil;
import com.huashi.dealer.modular.business.express.service.ExpressService;
import com.huashi.dealer.modular.business.goods.mapper.GoodsImageMapper;
import com.huashi.dealer.modular.business.goods.mapper.GoodsSkuMapper;
import com.huashi.dealer.modular.business.message.mapper.MessageMapper;
import com.huashi.dealer.modular.business.order.bo.OrderSendBo;
import com.huashi.dealer.modular.business.order.enums.*;
import com.huashi.dealer.modular.business.order.mapper.StoreOrderMapper;
import com.huashi.dealer.modular.business.order.param.StoreOrderListParam;
import com.huashi.dealer.modular.business.order.param.OrderDeliveryParam;
import com.huashi.dealer.modular.business.order.param.OrderPriceUpdateParam;
import com.huashi.dealer.modular.business.order.param.OrderAuditParam;
import com.huashi.dealer.modular.business.order.template.OrderExpressTemplate;
import com.huashi.dealer.modular.business.region.mapper.RegionMapper;
import com.huashi.dealer.modular.business.upload.mapper.UploadFileMapper;
import com.huashi.dealer.modular.business.order.service.OrderExpressService;
import com.huashi.dealer.modular.business.order.service.OrderService;
import com.huashi.dealer.modular.business.order.service.StoreOrderService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huashi.dealer.modular.business.order.vo.StoreOrderListVo;
import com.huashi.dealer.modular.business.order.vo.StoreOrderDetailVo;
import com.huashi.dealer.modular.business.user.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.math.BigDecimal;
import java.math.RoundingMode;

import com.huashi.dealer.modular.business.order.vo.OrderExportVo;
import com.alibaba.excel.EasyExcel;
import java.io.ByteArrayOutputStream;
import com.huashi.dealer.modular.business.order.service.OrderGoodsService;
import cn.dev33.satoken.stp.StpUtil;
import com.huashi.dealer.modular.business.user.service.UserService;
import com.huashi.dealer.modular.business.order.mapper.OrderGoodsMapper;
import com.huashi.dealer.modular.business.message.service.MessageService;
import com.huashi.dealer.commonEntity.OrderGoods;
import com.huashi.dealer.commonEntity.Message;
import com.huashi.dealer.commonEntity.UserBalanceLog;
import com.huashi.dealer.commonEntity.UserRebateLog;
import com.huashi.dealer.commonEntity.UserWriteoffLog;
import com.huashi.dealer.modular.business.user.mapper.UserBalanceLogMapper;
import com.huashi.dealer.modular.business.user.mapper.UserRebateLogMapper;
import com.huashi.dealer.modular.business.user.mapper.UserWriteoffLogMapper;
import org.springframework.web.multipart.MultipartFile;

/**
 * Store端订单服务实现类
 * 对应PHP项目的订单管理功能
 *
 * @author 谭陈强
 * @since 2025-08-15
 */
@Slf4j
@Service
public class StoreOrderServiceImpl extends ServiceImpl<StoreOrderMapper, Order> implements StoreOrderService {
    
    @Resource
    private StoreOrderMapper storeOrderMapper;

    @Resource
    private UserMapper userMapper;
    @Autowired
    private GoodsImageMapper goodsImageMapper;
    
    @Resource
    private OrderGoodsService orderGoodsService;

    @Resource
    private UserService userService;
    @Resource
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private MessageMapper messageMapper;
    
    @Resource
    private MessageService messageService;
    @Resource
    private ExpressService expressService;
    
    @Resource
    private UserBalanceLogMapper userBalanceLogMapper;
    
    @Resource
    private UserRebateLogMapper userRebateLogMapper;
    
    @Resource
    private UserWriteoffLogMapper userWriteoffLogMapper;
    @Autowired
    private OrderExpressService orderExpressService;
    @Autowired
    private OrderService orderService;
    @Resource
    private RegionMapper regionMapper;

    @Resource
    private UploadFileMapper uploadFileMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private GoodsSkuMapper goodsSkuMapper;
    @Resource
    private DataScopeInfo dataScopeInfo;


    @Override
    public Page<StoreOrderListVo> getOrderList(StoreOrderListParam param, Page<StoreOrderListVo> page) {
        try {

            
            // 构建查询条件
            LambdaQueryWrapper<Order> queryWrapper = buildQueryWrapper(param);
            
            // 创建Order类型的分页对象进行查询
            Page<Order> orderPage = new Page<>(page.getCurrent(), page.getSize());
            // 分页查询订单
            orderPage = this.page(orderPage, queryWrapper);

            // 转换为VO
            Page<StoreOrderListVo> resultPage = new Page<>();
            BeanUtils.copyProperties(orderPage, resultPage);
            
            List<StoreOrderListVo> voList = orderPage.getRecords().stream()
                .map(this::convertToOrderListVo)
                .collect(Collectors.toList());
            
            resultPage.setRecords(voList);
            return resultPage;
            
        } catch (Exception e) {
            log.error("查询订单列表失败", e);
            throw new CommonException("查询订单列表失败：" + e.getMessage());
        }
    }

    @Override
    public StoreOrderDetailVo getOrderDetail(Long orderId) {
        try {

            
            // 查询订单基本信息
            Order order = this.getById(orderId);
            if (order == null) {
                throw new CommonException("订单不存在");
            }
            
            // 转换为详情VO
            StoreOrderDetailVo detailVo = convertToOrderDetailVo(order);
            
            // 查询订单商品信息
            List<OrderGoods> orderGoods = storeOrderMapper.selectOrderGoods(orderId);
            if (orderGoods != null && !orderGoods.isEmpty()) {
                List<StoreOrderDetailVo.OrderGoodsDetailVo> goodsList = orderGoods.stream()
                    .map(this::convertToOrderGoodsDetailVo)
                    .collect(Collectors.toList());
                detailVo.setGoods(goodsList);
            }

            // 查询用户信息
            User user = userMapper.selectById(order.getUserId().longValue());
            if (user != null) {
                StoreOrderDetailVo.OrderUserDetailVo userVo = convertToOrderUserDetailVo(user);
                detailVo.setUser(userVo);
            }

            // 查询订单地址信息
            OrderAddress orderAddress = storeOrderMapper.selectOrderAddress(orderId);
            if (orderAddress != null) {
                StoreOrderDetailVo.OrderAddressVo addressVo = convertToOrderAddressVo(orderAddress);
                detailVo.setAddress(addressVo);
            }
            
            // 查询订单物流信息
            List<OrderExpress> orderExpressList = storeOrderMapper.selectOrderExpress(orderId);
            if (orderExpressList != null && !orderExpressList.isEmpty()) {
                List<StoreOrderDetailVo.OrderExpressVo> expressList = orderExpressList.stream()
                    .map(this::convertToOrderExpressVo)
                    .collect(Collectors.toList());
                detailVo.setOrderExpress(expressList);
            }
            
            // 查询自提门店信息（如果是自提订单）
            if (order.getDeliveryType() != null && order.getDeliveryType() == 20 && order.getExtractShopId() != null) {
                Map<String, Object> shopInfo = storeOrderMapper.selectExtractShop(Long.valueOf(order.getExtractShopId()));
                if (shopInfo != null) {
                    StoreOrderDetailVo.ExtractShopVo shopVo = convertToExtractShopVo(shopInfo);
                    detailVo.setExtractShop(shopVo);
                }
            }
            
            return detailVo;
            
        } catch (Exception e) {
            log.error("查询订单详情失败，订单ID: {}", orderId, e);
            throw new CommonException("查询订单详情失败：" + e.getMessage());
        }
    }

    @Override
    public byte[] exportOrders(StoreOrderListParam param) {
        try {
            log.info("导出订单数据，参数: {}", param);
            
            // 构建查询条件 - 与list接口完全一致的逻辑
            LambdaQueryWrapper<Order> queryWrapper = buildQueryWrapper(param);
            
            // 查询所有符合条件的订单（不分页）
            List<Order> orders = this.list(queryWrapper);
            
            if (orders == null || orders.isEmpty()) {
                throw new CommonException("没有找到符合条件的订单数据");
            }
            
            // 转换为导出VO
            List<OrderExportVo> exportData = new ArrayList<>();
            for (Order order : orders) {
                // 查询订单商品信息
                List<OrderGoods> orderGoods = storeOrderMapper.selectOrderGoods(order.getOrderId().longValue());
                if (orderGoods != null && !orderGoods.isEmpty()) {
                    for (OrderGoods goods : orderGoods) {
                        OrderExportVo vo = convertToOrderExportVo(order, goods);
                        exportData.add(vo);
                    }
                } else {
                    // 如果没有商品信息，创建一个空的商品记录
                    OrderExportVo vo = convertToOrderExportVo(order, null);
                    exportData.add(vo);
                }
            }
            
            // 生成文件名 - 根据订单类型生成不同的文件名
            String fileName = generateExportFileName(param);
            
            // 执行Excel导出，返回字节数组
            return exportToExcelBytes(exportData, fileName);
            
        } catch (Exception e) {
            log.error("导出订单数据失败", e);
            throw new CommonException("导出订单数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 转换为订单导出VO
     */
    private OrderExportVo convertToOrderExportVo(Order order, OrderGoods orderGoods) {
        OrderExportVo vo = new OrderExportVo();
        
        // 订单基本信息
        vo.setOrderNo(order.getOrderNo());
        vo.setOrderTotalPrice(order.getTotalPrice() != null ? order.getTotalPrice().setScale(2, RoundingMode.HALF_UP) : null);
        vo.setPayPrice(order.getPayPrice() != null ? order.getPayPrice().setScale(2, RoundingMode.HALF_UP) : null);
        vo.setCreateTime(TimeUtil.changeToLocalDateTime(order.getCreateTime()));
        
        // 商品信息
        if (orderGoods != null) {
            vo.setGoodsNo(orderGoods.getGoodsNo());
            vo.setGoodsName(orderGoods.getGoodsName());
            vo.setGoodsSkuSpec(orderGoods.getGoodsSkuSpec());
            vo.setGoodsMoney(orderGoods.getGoodsMoney() != null ? orderGoods.getGoodsMoney().setScale(2, RoundingMode.HALF_UP) : null);
            vo.setGoodsPrice(orderGoods.getGoodsPrice() != null ? orderGoods.getGoodsPrice().setScale(2, RoundingMode.HALF_UP) : null);
            vo.setTotalNum(orderGoods.getTotalNum());
            vo.setTotalPrice(orderGoods.getTotalPrice() != null ? orderGoods.getTotalPrice().setScale(2, RoundingMode.HALF_UP) : null);
            vo.setBarCode(orderGoods.getBarCode());
        }
        
        // 用户信息
        User user = userMapper.selectById(order.getUserId().longValue());
        if (user != null) {
            vo.setBuyerName(user.getNickName() != null ? user.getNickName() : user.getRealName());
        }
        
        // 买家留言
        vo.setBuyerRemark(order.getBuyerRemark());
        
        // 收货地址信息
        OrderAddress orderAddress = storeOrderMapper.selectOrderAddress(order.getOrderId().longValue());
        if (orderAddress != null) {
            vo.setReceiverName(orderAddress.getName());
            vo.setReceiverPhone(orderAddress.getPhone());
            vo.setReceiverAddress(buildFullAddress(orderAddress));
        }
        
        // 状态信息
        vo.setOrderStatusText(OrderStatusEnum.getNameByValue(order.getOrderStatus()));
        vo.setDeliveryStatusText(DeliveryStatusEnum.getNameByValue(order.getDeliveryStatus()));
        
        // 发货时间
        if (order.getDeliveryTime() != null) {
            vo.setDeliveryTime(TimeUtil.changeToLocalDateTime(order.getDeliveryTime()));
        }
        
        return vo;
    }
    
    /**
     * 构建完整地址
     */
    private String buildFullAddress(OrderAddress address) {
        if (address == null) {
            return "";
        }
        
        StringBuilder fullAddress = new StringBuilder();
        
        // 这里可以根据实际需求查询地区名称
        // 暂时使用ID，后续可以优化为查询地区名称
        if (address.getProvinceId() != null) {
            fullAddress.append("省份ID:").append(address.getProvinceId()).append(" ");
        }
        if (address.getCityId() != null) {
            fullAddress.append("城市ID:").append(address.getCityId()).append(" ");
        }
        if (address.getRegionId() != null) {
            fullAddress.append("区域ID:").append(address.getRegionId()).append(" ");
        }
        
        if (address.getDetail() != null) {
            fullAddress.append(address.getDetail());
        }
        
        return fullAddress.toString().trim();
    }
    
    /**
     * 生成导出文件名
     */
    private String generateExportFileName(StoreOrderListParam param) {
        StringBuilder fileName = new StringBuilder("order-");
        
        // 根据订单类型添加标识
        if (param.getOrderType() != null) {
            switch (param.getOrderType()) {
                case StoreOrderListParam.TYPE_DELIVERY:
                    fileName.append("delivery-");
                    break;
                case StoreOrderListParam.TYPE_AUDIT:
                    fileName.append("audit-");
                    break;
                case StoreOrderListParam.TYPE_RECEIPT:
                    fileName.append("receipt-");
                    break;
                case StoreOrderListParam.TYPE_PAY:
                    fileName.append("pay-");
                    break;
                case StoreOrderListParam.TYPE_COMPLETE:
                    fileName.append("complete-");
                    break;
                case StoreOrderListParam.TYPE_CANCEL:
                    fileName.append("cancel-");
                    break;
                default:
                    fileName.append("all-");
                    break;
            }
        } else {
            fileName.append("all-");
        }
        
        // 添加时间戳
        fileName.append(System.currentTimeMillis());
        
        return fileName.toString();
    }
    
    /**
     * 导出到Excel，返回字节数组
     */
    private byte[] exportToExcelBytes(List<OrderExportVo> data, String fileName) {
        try {
            // 使用EasyExcel导出到字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            
            EasyExcel.write(outputStream, OrderExportVo.class)
                .sheet("订单数据")
                .doWrite(data);
            
            byte[] bytes = outputStream.toByteArray();
            outputStream.close();
            
            log.info("Excel导出成功，数据量: {}, 文件名: {}", data.size(), fileName);
            return bytes;
            
        } catch (Exception e) {
            log.error("Excel导出失败", e);
            throw new CommonException("Excel导出失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmDelivery(Long orderId, OrderDeliveryParam param) {
        try {
            log.info("确认发货，订单ID: {}, 参数: {}", orderId, param);
            
            // 查询订单
            Order order = this.getById(orderId);
            if (order == null) {
                throw new CommonException("订单不存在");
            }
            
            // 检查订单状态
            if (order.getPayStatus() != 20) {
                throw new CommonException("订单未付款，无法发货");
            }
            
            if (order.getAuditStatus() != 20) {
                throw new CommonException("订单未审核通过，无法发货");
            }
            
            // TODO: 实现发货逻辑
            // 1. 更新订单发货状态
            // 2. 记录物流信息
            // 3. 发送通知等
            
            log.info("订单发货成功，订单ID: {}", orderId);
            
        } catch (Exception e) {
            log.error("确认发货失败，订单ID: {}", orderId, e);
            throw new CommonException("发货失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderPrice(Long orderId, OrderPriceUpdateParam param) {
        try {
            log.info("修改订单价格，订单ID: {}, 参数: {}", orderId, param);
            
            // 查询订单
            Order order = this.getById(orderId);
            if (order == null) {
                throw new CommonException("订单不存在");
            }
            
            // 检查订单状态
            if (order.getPayStatus() == 20) {
                throw new CommonException("订单已付款，无法修改价格");
            }
            
            // TODO: 实现价格修改逻辑
            // 1. 更新订单价格
            // 2. 记录价格变更日志
            // 3. 重新计算订单总金额等
            
            log.info("订单价格修改成功，订单ID: {}", orderId);
            
        } catch (Exception e) {
            log.error("修改订单价格失败，订单ID: {}", orderId, e);
            throw new CommonException("修改失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initialAudit(Long orderId, OrderAuditParam param) {
        try {
            // 查询订单
            Order order = this.getById(orderId);
            if (order == null) {
                throw new CommonException("订单不存在");
            }
            
            // 检查订单状态
            if (order.getOrderStatus() != 10) {
                throw new CommonException("订单状态异常，无法审核");
            }
            
            // 检查审核状态
            if (order.getAuditStatus() != 30) {
                throw new CommonException("订单审核状态异常，无法进行初审");
            }
            
            // 根据审核结果处理
            if (param.getAuditStatus() == 20) {
                // 审核通过 - 包含商品数量修改和价格重新计算
                handleAuditApproved(order, param);
            } else if (param.getAuditStatus() == 40) {
                // 审核驳回
                handleAuditRejected(order, param);
            } else {
                throw new CommonException("无效的审核状态");
            }
            
            log.info("订单初审成功，订单ID: {}, 审核结果: {}", orderId, 
                    param.getAuditStatus() == 20 ? "通过" : "驳回");
            
        } catch (Exception e) {
            log.error("初审订单失败，订单ID: {}", orderId, e);
            throw new CommonException("初审失败：" + e.getMessage());
        }
    }
    
    /**
     * 处理审核通过（包含商品数量修改和价格重新计算）
     */
    private void handleAuditApproved(Order order, OrderAuditParam param) {
        // 如果包含商品数量修改，则进行价格重新计算
        if (param.getGoodsNum() != null && !param.getGoodsNum().isEmpty()) {

            recalculateOrderPrice(order, param);
        }
        
        // 更新订单审核状态为初审通过
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getOrderId, order.getOrderId())
                .set(Order::getAuditStatus, AuditStatusEnum.PENDING.getValue())
                .set(Order::getAuditTime, System.currentTimeMillis() / 1000)
                .set(Order::getUpdateTime, System.currentTimeMillis() / 1000);
        
        if (StrUtil.isNotBlank(param.getAuditRemark())) {
            updateWrapper.set(Order::getRejectReason, param.getAuditRemark());
        }
        
        boolean success = this.update(updateWrapper);
        if (!success) {
            throw new CommonException("订单状态更新失败");
        }
        
        // 发送审核通过消息通知
//        sendOrderAuditMessage(order, AuditStatusEnum.FIRST_APPROVED.getValue(), null);
    }
    
    /**
     * 重新计算订单价格（对应PHP版本的核心逻辑）
     */
    private void recalculateOrderPrice(Order order, OrderAuditParam param) {
        try {
            // 查询订单商品信息
            List<OrderGoods> orderGoodsList = storeOrderMapper.selectOrderGoods(order.getOrderId().longValue());
            if (orderGoodsList == null || orderGoodsList.isEmpty()) {
                throw new CommonException("订单商品信息不存在");
            }
            
            BigDecimal totalPrice = BigDecimal.ZERO;
            boolean hasDeletedGoods = false;
            
            // 处理每个商品的数量修改
            for (OrderGoods orderGoods : orderGoodsList) {

                Long goodsId = Long.valueOf(orderGoods.getGoodsId());
                Integer newQuantity = param.getGoodsNum().get(goodsId);
                
                if (newQuantity == null) {
                    // 如果没有指定新数量，保持原数量
                    newQuantity = orderGoods.getTotalNum();
                }
                
                // 验证数量不能超过原订单数量
                if (newQuantity > orderGoods.getTotalNum()) {
                    throw new CommonException(String.format("商品[%s]数量不能大于下单时购买的数量", orderGoods.getGoodsName()));
                }
                
                // 更新订单商品信息
                LambdaUpdateWrapper<OrderGoods> goodsUpdateWrapper = new LambdaUpdateWrapper<>();
                goodsUpdateWrapper.eq(OrderGoods::getOrderGoodsId, orderGoods.getOrderGoodsId());
                
                if (newQuantity == 0) {
                    // 数量为0，标记为删除
                    goodsUpdateWrapper.set(OrderGoods::getIsDelete, 1);
                    hasDeletedGoods = true;
                } else {
                    // 计算新的商品价格
                    BigDecimal newGoodsPrice = calculateGoodsPrice(orderGoods, newQuantity);
                    
                    goodsUpdateWrapper.set(OrderGoods::getTotalNum, newQuantity)
                            .set(OrderGoods::getTotalPrice, newGoodsPrice)
                            .set(OrderGoods::getTotalPayPrice, newGoodsPrice);
                    
                    totalPrice = totalPrice.add(newGoodsPrice);
                }
                
                // 更新订单商品
                boolean goodsUpdateSuccess = orderGoodsService.update(goodsUpdateWrapper);
                if (!goodsUpdateSuccess) {
                    throw new CommonException("更新订单商品信息失败");
                }
            }
            
            // 如果所有商品都被删除，则删除整个订单
            if (hasDeletedGoods && param.getGoodsNum().values().stream().allMatch(num -> num == 0)) {
                LambdaUpdateWrapper<Order> deleteWrapper = new LambdaUpdateWrapper<>();
                deleteWrapper.eq(Order::getOrderId, order.getOrderId())
                        .set(Order::getIsDelete, 1);
                
                boolean deleteSuccess = this.update(deleteWrapper);
                if (!deleteSuccess) {
                    throw new CommonException("删除订单失败");
                }
                return;
            }
            
            // 更新订单总价
            LambdaUpdateWrapper<Order> priceUpdateWrapper = new LambdaUpdateWrapper<>();
            priceUpdateWrapper.eq(Order::getOrderId, order.getOrderId())
                    .set(Order::getTotalPrice, totalPrice)
                    .set(Order::getOrderPrice, totalPrice)
                    .set(Order::getPayPrice, totalPrice);
            
            boolean priceUpdateSuccess = this.update(priceUpdateWrapper);
            if (!priceUpdateSuccess) {
                throw new CommonException("更新订单价格失败");
            }
            
            log.info("订单价格重新计算完成，订单ID: {}, 新总价: {}", order.getOrderId(), totalPrice);
            
        } catch (Exception e) {
            log.error("重新计算订单价格失败，订单ID: {}", order.getOrderId(), e);
            throw new CommonException("重新计算订单价格失败：" + e.getMessage());
        }
    }
    
    /**
     * 计算商品价格（包含活动商品优惠计算）
     */
    private BigDecimal calculateGoodsPrice(OrderGoods orderGoods, Integer quantity) {
        try {
            // 检查是否是活动商品
            if (orderGoods.getDiscountActivePrice() != null && orderGoods.getDiscountActivePrice().compareTo(BigDecimal.ZERO) > 0) {
                // 活动商品，使用活动价格
                return calculateActiveGoodsPrice(orderGoods, quantity);
            } else {
                // 普通商品，使用基础价格
                BigDecimal basePrice = orderGoods.getGoodsPrice();
                if (basePrice == null) {
                    basePrice = BigDecimal.ZERO;
                }
                return basePrice.multiply(new BigDecimal(quantity));
            }
        } catch (Exception e) {
            log.error("计算商品价格失败，商品ID: {}, 数量: {}", orderGoods.getGoodsId(), quantity, e);
            // 如果计算失败，使用基础价格
            BigDecimal basePrice = orderGoods.getGoodsPrice();
            if (basePrice == null) {
                basePrice = BigDecimal.ZERO;
            }
            return basePrice.multiply(new BigDecimal(quantity));
        }
    }
    
    /**
     * 计算活动商品价格（对应PHP版本的discount_active逻辑）
     */
    private BigDecimal calculateActiveGoodsPrice(OrderGoods orderGoods, Integer quantity) {
        try {
            // 获取活动商品信息
            Map<String, Object> activeGoodsInfo = getActiveGoodsInfo(Long.valueOf(orderGoods.getGoodsId()));
            if (activeGoodsInfo == null) {
                // 不是活动商品，使用基础价格
                BigDecimal basePrice = orderGoods.getGoodsPrice();
                if (basePrice == null) {
                    basePrice = BigDecimal.ZERO;
                }
                return basePrice.multiply(new BigDecimal(quantity));
            }
            
            // 验证起订量
            Integer minQuantity = (Integer) activeGoodsInfo.get("set_num");
            if (minQuantity != null && quantity < minQuantity) {
                throw new CommonException(String.format("商品[%s]活动起订量为%d，当前数量%d不足", 
                        orderGoods.getGoodsName(), minQuantity, quantity));
            }
            
            // 获取阶梯价格
            BigDecimal activePrice = getActiveGoodsPrice(Long.valueOf(orderGoods.getGoodsId()), quantity);
            if (activePrice == null || activePrice.compareTo(BigDecimal.ZERO) <= 0) {
                // 如果没有活动价格，回退到基础价格
                BigDecimal basePrice = orderGoods.getGoodsPrice();
                if (basePrice == null) {
                    basePrice = BigDecimal.ZERO;
                }
                return basePrice.multiply(new BigDecimal(quantity));
            }
            
            return activePrice.multiply(new BigDecimal(quantity));
            
        } catch (Exception e) {
            log.error("计算活动商品价格失败，商品ID: {}, 数量: {}", orderGoods.getGoodsId(), quantity, e);
            // 如果计算失败，使用基础价格
            BigDecimal basePrice = orderGoods.getGoodsPrice();
            if (basePrice == null) {
                basePrice = BigDecimal.ZERO;
            }
            return basePrice.multiply(new BigDecimal(quantity));
        }
    }
    
    /**
     * 获取活动商品信息
     */
    private Map<String, Object> getActiveGoodsInfo(Long goodsId) {
        try {
            // 查询活动商品信息
            // 对应PHP版本的ActiveGoodsModel查询
            Map<String, Object> activeGoodsInfo = storeOrderMapper.selectActiveGoodsInfo(goodsId);
            if (activeGoodsInfo == null) {
                return null;
            }
            
            // 查询活动规则信息
            // 对应PHP版本的ActiveModel查询
            Map<String, Object> activeRule = storeOrderMapper.selectActiveRule(
                Long.valueOf(activeGoodsInfo.get("discount_id").toString())
            );
            
            if (activeRule != null) {
                // 合并活动规则信息
                activeGoodsInfo.putAll(activeRule);
            }
            
            return activeGoodsInfo;
            
        } catch (Exception e) {
            log.error("查询活动商品信息失败，商品ID: {}", goodsId, e);
            return null;
        }
    }
    
    /**
     * 计算活动商品价格（阶梯价格计算）
     * 
     * 阶梯价格计算逻辑：
     * 1. 查询商品是否参与活动
     * 2. 验证商品数量是否满足起订量
     * 3. 根据商品数量查找合适的阶梯价格规格
     * 4. 选择数量小于等于当前商品数量，且数量最大的规格
     * 
     * 例如：
     * - 阶梯规格：10件起订，价格8元；20件起订，价格7元；50件起订，价格6元
     * - 如果购买15件：选择10件规格，价格为8元
     * - 如果购买25件：选择20件规格，价格为7元
     * - 如果购买60件：选择50件规格，价格为6元
     */
    private BigDecimal getActiveGoodsPrice(Long goodsId, Integer quantity) {
        try {
            // 查询活动商品信息
            Map<String, Object> activeGoodsInfo = getActiveGoodsInfo(goodsId);
            if (activeGoodsInfo == null) {
                return null;
            }
            
            Long discountId = Long.valueOf(activeGoodsInfo.get("discount_id").toString());
            
            // 查询阶梯价格规格
            // 对应PHP版本的ActiveSpecModel查询
            List<Map<String, Object>> activeSpecs = storeOrderMapper.selectActiveSpecs(discountId);
            if (activeSpecs == null || activeSpecs.isEmpty()) {
                return null;
            }
            
            // 根据数量查找合适的阶梯价格
            // 对应PHP版本的逻辑：where(['discount_id' => $discount_active[$k]['discount_id'], "num" => ['<=', $discount_active[$k]['new_active_goods_num']]])->order("id desc")->find()
            BigDecimal bestPrice = null;
            Integer bestNum = 0;
            
            for (Map<String, Object> spec : activeSpecs) {
                Integer specNum = Integer.valueOf(spec.get("num").toString());
                BigDecimal specPrice = new BigDecimal(spec.get("price").toString());
                
                // 找到数量小于等于当前商品数量，且数量最大的规格
                if (specNum <= quantity && specNum > bestNum) {
                    bestNum = specNum;
                    bestPrice = specPrice;
                }
            }
            
            if (bestPrice != null) {
                log.info("活动商品阶梯价格计算成功，商品ID: {}, 数量: {}, 阶梯数量: {}, 价格: {}", 
                        goodsId, quantity, bestNum, bestPrice);
                return bestPrice;
            }
            
            return null;
            
        } catch (Exception e) {
            log.error("查询活动商品阶梯价格失败，商品ID: {}, 数量: {}", goodsId, quantity, e);
            return null;
        }
    }
    
    /**
     * 处理审核驳回
     */
    private void handleAuditRejected(Order order, OrderAuditParam param) {
        param.setRejectReason(param.getAuditRemark());
        // 验证驳回原因
        if (StrUtil.isBlank(param.getRejectReason())) {
            throw new CommonException("驳回时必须填写驳回原因");
        }
        
        // 更新订单审核状态为初审驳回
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getOrderId, order.getOrderId())
                .set(Order::getAuditStatus, AuditStatusEnum.FIRST_REJECTED.getValue())
                .set(Order::getOrderStatus, 20)
                .set(Order::getAuditTime, System.currentTimeMillis() / 1000)
                .set(Order::getRejectReason, param.getRejectReason())
                .set(Order::getUpdateTime, System.currentTimeMillis() / 1000);
        
        boolean success = this.update(updateWrapper);
        if (!success) {
            throw new CommonException("订单状态更新失败");
        }
        
        // 发送审核驳回消息通知
        sendOrderAuditMessage(order, AuditStatusEnum.FIRST_REJECTED.getValue(), param.getRejectReason());
        
        // TODO: 记录审核日志
        // TODO: 处理退款（如果已付款）
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finalAudit(Long orderId, OrderAuditParam param) {
        try {
            
            // 查询订单
            Order order = this.getById(orderId);
            if (order == null) {
                throw new CommonException("订单不存在");
            }
            
            // 检查订单状态
            if (order.getOrderStatus() != 10) {
                throw new CommonException("订单状态异常，无法审核");
            }
            
            // 检查审核状态
            if (order.getAuditStatus() != 0) {
                throw new CommonException("订单审核状态异常，无法复审");
            }
            
            // 检查发货状态
            if (order.getDeliveryStatus() == 20) {
                throw new CommonException("已发货订单不可审核");
            }
            
            // 获取当前登录用户信息
            Long auditorId = Long.valueOf(order.getUserId());
            User byId = userService.getById(auditorId);

            // 根据审核结果处理
            if (param.getAuditStatus() == 40) {
                // 审核驳回
                handleAuditReject(order, param, auditorId, byId.getNickName());
            } else if (param.getAuditStatus() == 20) {
                // 审核通过
                handleAuditApprove(order, param, auditorId, byId.getNickName());
            } else {
                throw new CommonException("无效的审核状态");
            }
            
        } catch (Exception e) {
            log.error("复审订单失败，订单ID: {}", orderId, e);
            throw new CommonException("复审失败：" + e.getMessage());
        }
    }
    
    /**
     * 处理审核驳回
     */
    private void handleAuditReject(Order order, OrderAuditParam param, Long auditorId, String auditorName) {

        // 验证驳回原因
        if (StrUtil.isBlank(param.getAuditRemark())) {
            throw new CommonException("驳回时必须填写驳回原因");
        }
        param.setRejectReason(param.getAuditRemark());

        // 如果已支付，需要处理退款
        if (order.getPayStatus() == 20) {

            handleRefundForReject(order);
        }

        // 回退商品库存
        rollbackGoodsStock(order);

        // 回退用户优惠券
        if (order.getCouponId() != null && order.getCouponId() > 0) {

            rollbackUserCoupon(order.getCouponId());
        }

        // 回退用户积分
        if (order.getPointsNum() != null && order.getPointsNum() > 0) {

            rollbackUserPoints(order);
        }

        // 更新订单状态
        updateOrderForReject(order, param, auditorId, auditorName);

        // 记录审核日志
        recordAuditLog(order, param, auditorId, auditorName, "复审驳回");

        // 发送审核驳回消息通知
        sendOrderAuditMessage(order, param.getAuditStatus(), param.getRejectReason());
    }
    
    /**
     * 处理审核通过
     */
    private void handleAuditApprove(Order order, OrderAuditParam param, Long auditorId, String auditorName) {
        log.info("处理订单审核通过，订单ID: {}", order.getOrderId());
        
        // 检查支付方式相关的余额是否足够
        checkPaymentBalance(order);
        
        // 处理支付逻辑
        handlePaymentForApprove(order);
        
        // 更新订单状态
        updateOrderForApprove(order, param, auditorId, auditorName);
        
        // 记录审核日志
        recordAuditLog(order, param, auditorId, auditorName, "复审通过");
        
        // 发送审核通过消息通知
        sendOrderAuditMessage(order, param.getAuditStatus(), null);
    }
    
    /**
     * 处理驳回时的退款
     */
    private void handleRefundForReject(Order order) {
        log.info("处理订单驳回退款，订单ID: {}", order.getOrderId());
        
        try {
            // TODO: 调用退款服务执行退款
            // refundService.executeRefund(order);
            
            // 暂时记录日志，等待退款服务实现
            log.info("订单驳回退款处理完成，订单ID: {}", order.getOrderId());
            
        } catch (Exception e) {
            log.error("处理订单驳回退款失败，订单ID: {}", order.getOrderId(), e);
            throw new CommonException("退款处理失败：" + e.getMessage());
        }
    }
    
    /**
     * 回退商品库存
     */
    private void rollbackGoodsStock(Order order) {
        log.info("回退商品库存，订单ID: {}", order.getOrderId());
        
        try {
            // 查询订单商品
            List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(
                new LambdaQueryWrapper<OrderGoods>()
                    .eq(OrderGoods::getOrderId, order.getOrderId())
                    .eq(OrderGoods::getIsDelete, 0)
            );
            
            for (OrderGoods orderGoods : orderGoodsList) {
                // TODO: 调用库存服务回退库存
                // stockService.rollbackStock(orderGoods.getGoodsId(), orderGoods.getTotalNum());
                
                log.info("回退商品库存，商品ID: {}, 数量: {}", 
                        orderGoods.getGoodsId(), orderGoods.getTotalNum());
            }
            
        } catch (Exception e) {
            log.error("回退商品库存失败，订单ID: {}", order.getOrderId(), e);
            throw new CommonException("库存回退失败：" + e.getMessage());
        }
    }
    
    /**
     * 回退用户优惠券
     */
    private void rollbackUserCoupon(Integer couponId) {
        log.info("回退用户优惠券，优惠券ID: {}", couponId);
        
        try {
            // TODO: 调用优惠券服务回退优惠券
            // userCouponService.rollbackCoupon(couponId);
            
            log.info("用户优惠券回退完成，优惠券ID: {}", couponId);
            
        } catch (Exception e) {
            log.error("回退用户优惠券失败，优惠券ID: {}", couponId, e);
            throw new CommonException("优惠券回退失败：" + e.getMessage());
        }
    }
    
    /**
     * 回退用户积分
     */
    private void rollbackUserPoints(Order order) {
        log.info("回退用户积分，订单ID: {}, 积分数量: {}", order.getOrderId(), order.getPointsNum());
        
        try {
            // TODO: 调用用户服务回退积分
            // userService.rollbackPoints(order.getUserId(), order.getPointsNum(), 
            //     "订单取消：" + order.getOrderNo());
            
            log.info("用户积分回退完成，订单ID: {}", order.getOrderId());
            
        } catch (Exception e) {
            log.error("回退用户积分失败，订单ID: {}", order.getOrderId(), e);
            throw new CommonException("积分回退失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查支付余额是否足够
     */
    private void checkPaymentBalance(Order order) {
        log.info("检查支付余额，订单ID: {}", order.getOrderId());
        
        try {
            // 查询用户信息
            User user = userService.getById(order.getUserId());
            if (user == null) {
                throw new CommonException("用户信息不存在");
            }
            
            // 检查返利支付余额
            if (order.getPayType() != null && order.getPayType() == 30) { // 假设30是返利支付
                if (user.getRebate().compareTo(order.getPayPrice()) < 0) {
                    throw new CommonException("返利余额不足，无法使用返利支付");
                }
            }
            
            // 检查核销支付余额
            if (order.getPayType() != null && order.getPayType() == 40) { // 假设40是核销支付
                if (user.getWriteoff().compareTo(order.getPayPrice()) < 0) {
                    throw new CommonException("核销余额不足，无法使用核销支付");
                }
            }
            
        } catch (Exception e) {
            log.error("检查支付余额失败，订单ID: {}", order.getOrderId(), e);
            throw new CommonException("支付余额检查失败：" + e.getMessage());
        }
    }
    
    /**
     * 处理审核通过时的支付逻辑
     * 根据支付方式扣减用户余额
     */
    private void handlePaymentForApprove(Order order) {
        log.info("处理审核通过支付逻辑，订单ID: {}, 支付方式: {}", order.getOrderId(), order.getPayType());
        
        try {
            // 查询用户信息
            User user = userService.getById(order.getUserId());
            if (user == null) {
                throw new CommonException("用户信息不存在");
            }
            
            // 根据支付方式扣减相应余额
            if (order.getPayType() != null) {
                switch (order.getPayType()) {
                    case 10: // 余额支付
                        // 扣减余额
                        user.setBalance(user.getBalance().subtract(order.getPayPrice()));
                        break;
                    case 30: // 返利支付
                        if (user.getRebate().compareTo(order.getPayPrice()) < 0) {
                            throw new CommonException("返利余额不足，无法完成支付");
                        }
                        // 扣减返利余额
                        user.setRebate(user.getRebate().subtract(order.getPayPrice()));
                        break;
                        
                    case 40: // 核销支付
                        if (user.getWriteoff().compareTo(order.getPayPrice()) < 0) {
                            throw new CommonException("核销余额不足，无法完成支付");
                        }
                        // 扣减核销余额
                        user.setWriteoff(user.getWriteoff().subtract(order.getPayPrice()));
                        break;
                        
                    case 20: // 微信支付 - 已通过微信支付，无需扣减余额
                        log.info("微信支付订单，无需扣减余额，订单ID: {}", order.getOrderId());
                        break;
                        
                    default:
                        log.warn("未知支付方式: {}, 订单ID: {}", order.getPayType(), order.getOrderId());
                        break;
                }
                
                // 更新用户余额
                user.setUpdateTime(System.currentTimeMillis() / 1000);
                boolean updateSuccess = userService.updateById(user);
                if (!updateSuccess) {
                    throw new CommonException("更新用户余额失败");
                }
                
                // 更新订单支付状态为已支付
                LambdaUpdateWrapper<Order> payUpdateWrapper = new LambdaUpdateWrapper<>();
                payUpdateWrapper.eq(Order::getOrderId, order.getOrderId())
                        .set(Order::getPayStatus, 20) // 已支付
                        .set(Order::getPayTime, System.currentTimeMillis() / 1000)
                        .set(Order::getUpdateTime, System.currentTimeMillis() / 1000);
                
                boolean orderUpdateSuccess = this.update(payUpdateWrapper);
                if (!orderUpdateSuccess) {
                    throw new CommonException("更新订单支付状态失败");
                }
                
                // 生成用户余额变动记录
                if (order.getPayType() == 10 || order.getPayType() == 30 || order.getPayType() == 40) {
                    createUserBalanceLog(order, user);
                }
                
            }
            
        } catch (Exception e) {
            log.error("处理审核通过支付失败，订单ID: {}", order.getOrderId(), e);
            throw new CommonException("支付处理失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新驳回订单状态
     */
    private void updateOrderForReject(Order order, OrderAuditParam param, Long auditorId, String auditorName) {
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getOrderId, order.getOrderId())
                    .set(Order::getAuditStatus, 10)
                    .set(Order::getOrderStatus, 20) // 订单取消
                    .set(Order::getAuditTime, (int) (System.currentTimeMillis() / 1000))
                    .set(Order::getRejectReason, param.getRejectReason())
                    .set(Order::getUpdateTime, (int) (System.currentTimeMillis() / 1000));
        
        boolean updateResult = this.update(updateWrapper);
        if (!updateResult) {
            throw new CommonException("更新订单状态失败");
        }
        
        log.info("订单驳回状态更新成功，订单ID: {}", order.getOrderId());
    }
    
    /**
     * 更新通过订单状态
     */
    private void updateOrderForApprove(Order order, OrderAuditParam param, Long auditorId, String auditorName) {
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getOrderId, order.getOrderId())
                    .set(Order::getAuditStatus, param.getAuditStatus())
                    .set(Order::getAuditTime, (int) (System.currentTimeMillis() / 1000))
                    .set(Order::getUpdateTime, (int) (System.currentTimeMillis() / 1000));
        
        boolean updateResult = this.update(updateWrapper);
        if (!updateResult) {
            throw new CommonException("更新订单状态失败");
        }
        
        log.info("订单通过状态更新成功，订单ID: {}", order.getOrderId());
    }
    
    /**
     * 记录审核日志
     */
    private void recordAuditLog(Order order, OrderAuditParam param, Long auditorId, String auditorName, String action) {
        try {
            // TODO: 调用日志服务记录审核日志
            // auditLogService.recordOrderAuditLog(order, param, auditorId, auditorName, action);
            
            log.info("审核日志记录完成，订单ID: {}, 操作: {}", order.getOrderId(), action);
            
        } catch (Exception e) {
            log.error("记录审核日志失败，订单ID: {}", order.getOrderId(), e);
            // 日志记录失败不影响主流程，只记录错误
        }
    }
    
    /**
     * 创建用户余额变动记录
     * 
     * @param order 订单信息
     * @param user 用户信息
     */
    private void createUserBalanceLog(Order order, User user) {
        try {
            long currentTime = System.currentTimeMillis() / 1000;
            
            if (order.getPayType() == 10) {
                // 基本余额支付 - 创建基本账户余额变动记录
                UserBalanceLog balanceLog = new UserBalanceLog();
                balanceLog.setUserId(Long.valueOf(order.getUserId()));
                balanceLog.setScene(20); // 20-用户消费
                balanceLog.setMoney(order.getPayPrice().negate()); // 负数表示扣减
                balanceLog.setDescription("订单支付扣减");
                balanceLog.setRemark("订单号：" + order.getOrderNo());
                balanceLog.setCreateTime(currentTime);
                userBalanceLogMapper.insert(balanceLog);
            } else if (order.getPayType() == 30) {
                // 返利支付 - 创建返利余额变动记录
                UserRebateLog rebateLog = new UserRebateLog();
                rebateLog.setUserId(Long.valueOf(order.getUserId()));
                rebateLog.setScene(20); // 20-用户消费
                rebateLog.setMoney(order.getPayPrice().negate()); // 负数表示扣减
                rebateLog.setRemark("订单支付扣减：" + order.getOrderNo());
                rebateLog.setCreateTime(currentTime);
                
                userRebateLogMapper.insert(rebateLog);
            } else if (order.getPayType() == 40) {
                // 核销支付 - 创建核销余额变动记录
                UserWriteoffLog writeoffLog = new UserWriteoffLog();
                writeoffLog.setUserId(Long.valueOf(order.getUserId()));
                writeoffLog.setScene(20); // 20-用户消费
                writeoffLog.setMoney(order.getPayPrice().negate()); // 负数表示扣减
                writeoffLog.setRemark("订单支付扣减：" + order.getOrderNo());
                writeoffLog.setCreateTime(currentTime);
                
                userWriteoffLogMapper.insert(writeoffLog);
            }
            
        } catch (Exception e) {
            log.error("创建用户余额变动记录失败，订单ID: {}, 用户ID: {}", order.getOrderId(), order.getUserId(), e);
            // 余额记录创建失败不影响主流程，只记录错误
        }
    }
    private void addUserBalanceLog(Order order, User user) {
        try {
            long currentTime = System.currentTimeMillis() / 1000;

            if (order.getPayType() == 10) {
                // 基本余额支付 - 创建基本账户余额变动记录
                UserBalanceLog balanceLog = new UserBalanceLog();
                balanceLog.setUserId(Long.valueOf(order.getUserId()));
                balanceLog.setScene(10); //
                balanceLog.setMoney(order.getPayPrice().negate()); // 负数表示扣减
                balanceLog.setDescription("订单取消增加");
                balanceLog.setRemark("订单号：" + order.getOrderNo());
                balanceLog.setCreateTime(currentTime);
                userBalanceLogMapper.insert(balanceLog);
            } else if (order.getPayType() == 30) {
                // 返利支付 - 创建返利余额变动记录
                UserRebateLog rebateLog = new UserRebateLog();
                rebateLog.setUserId(Long.valueOf(order.getUserId()));
                rebateLog.setScene(10);
                rebateLog.setMoney(order.getPayPrice()); // 负数表示扣减
                rebateLog.setRemark("订单取消增加：" + order.getOrderNo());
                rebateLog.setCreateTime(currentTime);

                userRebateLogMapper.insert(rebateLog);
            } else if (order.getPayType() == 40) {
                // 核销支付 - 创建核销余额变动记录
                UserWriteoffLog writeoffLog = new UserWriteoffLog();
                writeoffLog.setUserId(Long.valueOf(order.getUserId()));
                writeoffLog.setScene(10); // 20-用户消费
                writeoffLog.setMoney(order.getPayPrice()); // 负数表示扣减
                writeoffLog.setRemark("订单取消增加：" + order.getOrderNo());
                writeoffLog.setCreateTime(currentTime);

                userWriteoffLogMapper.insert(writeoffLog);
            }

        } catch (Exception e) {
            log.error("创建用户余额变动记录失败，订单ID: {}, 用户ID: {}", order.getOrderId(), order.getUserId(), e);
            // 余额记录创建失败不影响主流程，只记录错误
        }
    }
    /**
     * 发送订单审核消息通知
     * 
     * @param order 订单信息
     * @param auditStatus 审核状态
     * @param rejectReason 驳回原因
     */
    private void sendOrderAuditMessage(Order order, Integer auditStatus, String rejectReason) {
        try {
            Message message = new Message();
            message.setUserId(order.getUserId().intValue());
            message.setIsType(30); // 30-订单消息
            message.setStatus(0); // 0-未读
            message.setMessageStatus(1); // 1-显示
            message.setCreateTime(System.currentTimeMillis() / 1000);
            message.setUpdateTime(System.currentTimeMillis() / 1000);
            
            if (auditStatus == 40) {
                // 审核驳回
                message.setMessageTitle("订单审核通知");
                String content = String.format("您的订单[%s]审核未通过，请修改订单或联系业务员。未通过原因：%s", 
                    order.getOrderNo(), rejectReason != null ? rejectReason : "无");
                message.setMessageContent(content);
            } else if (auditStatus == 20) {
                // 审核通过
                message.setMessageTitle("订单审核通知");
                String content = String.format("您的订单[%s]审核已通过，订单将进入发货流程。", order.getOrderNo());
                message.setMessageContent(content);
            }
            
            // 发送消息
            messageService.save(message);
            log.info("订单审核消息发送成功，订单ID: {}, 审核状态: {}", order.getOrderId(), auditStatus);
            
        } catch (Exception e) {
            log.error("发送订单审核消息失败，订单ID: {}, 审核状态: {}", order.getOrderId(), auditStatus, e);
            // 消息发送失败不影响主流程，只记录错误
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditCancelOrder(Long orderId, OrderAuditParam param) {
        try {
            log.info("审核取消订单，订单ID: {}, 参数: {}", orderId, param);
            
            // 查询订单
            Order order = this.getById(orderId);
            if (order == null) {
                throw new CommonException("订单不存在");
            }
            User user= userMapper.selectById(order.getUserId());
            // 检查订单状态
            if (order.getOrderStatus() != 21) {
                throw new CommonException("订单状态异常，无法审核取消");
            }
            if(param.getAuditStatus()==20){
                // 订单审核通过
                passAuditCancelOrder(order,user,param);
            }else{
                LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(Order::getOrderStatus, 10).eq(Order::getOrderId, order.getOrderId());
                this.update(updateWrapper);
            }

            log.info("订单取消审核成功，订单ID: {}", orderId);
            
        } catch (Exception e) {
            log.error("审核取消订单失败，订单ID: {}", orderId, e);
            throw new CommonException("审核失败：" + e.getMessage());
        }
    }

    private void passAuditCancelOrder(Order order, User user, OrderAuditParam param) {
        if(order.getPayStatus() == 20){
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            if(order.getPayType() == 10){
                updateWrapper.eq(User::getUserId, order.getUserId())
                        .set(User::getBalance, user.getBalance().add(order.getPayPrice()));
            }
            if(order.getPayType() == 30){
                updateWrapper.eq(User::getUserId, order.getUserId())
                        .set(User::getRebate, user.getRebate().add(order.getPayPrice()));
            }
            if (order.getPayType() == 40){
                updateWrapper.eq(User::getUserId, order.getUserId())
                        .set(User::getWriteoff, user.getWriteoff().add(order.getPayPrice()));
            }
            userService.update(updateWrapper);
        }
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Order::getOrderStatus, 20).eq(Order::getOrderId, order.getOrderId());
        this.update(updateWrapper);
        addUserBalanceLog(order,user);
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<Order> buildQueryWrapper(StoreOrderListParam param) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();

        // 数据权限过滤
        // 业务员：只能查看自己的经销商订单
        // 业务主管：可以查看自己和下属业务员的经销商订单
        // 其他用户（管理员等）：可以查看所有订单
        List<Long> userIds = dataScopeInfo.filter();
        if (!userIds.contains(-1L)) {
            queryWrapper.in(Order::getUserId, userIds);
        }

        // 搜索条件：订单号或用户昵称
        if (StrUtil.isNotBlank(param.getSearch())) {
            queryWrapper.and(wrapper -> wrapper
                .like(Order::getOrderNo, param.getSearch())
                .or()
                .exists("SELECT 1 FROM yoshop_user u WHERE u.user_id = yoshop_order.user_id AND u.nick_name LIKE '%" + param.getSearch() + "%'")
            );
        }
        
        // 时间范围筛选
        if (param.getStartTime() != null) {
            queryWrapper.ge(Order::getCreateTime, TimeUtil.localDateToTimestamp(param.getStartTime()));
        }
        if (param.getEndTime() != null) {
            queryWrapper.lt(Order::getCreateTime, TimeUtil.localDateToTimestamp(param.getEndTime().plusDays(1)));
        }
        
        // 审核状态筛选
        if (param.getAuditStatus() != null && param.getAuditStatus() > 0) {
            if (param.getAuditStatus() == 21) {
                queryWrapper.eq(Order::getOrderStatus, 21);
            } else if (param.getAuditStatus() == 30) {
                queryWrapper.and(wrapper -> wrapper
                    .eq(Order::getOrderStatus, 10)
                    .eq(Order::getAuditStatus, 30)
                );
            } else if (param.getAuditStatus() == 40) {
                queryWrapper.and(wrapper -> wrapper
                    .eq(Order::getOrderStatus, 10)
                    .eq(Order::getAuditStatus, 0)
                );
            }
        }
        
        // 支付类型筛选
        if (param.getPayType() != null && param.getPayType() > 0) {
            queryWrapper.eq(Order::getPayType, param.getPayType());
        }

        // 配送方式筛选
        if (param.getDeliveryType() != null && param.getDeliveryType() > 0) {
            queryWrapper.eq(Order::getDeliveryType, param.getDeliveryType());
        }

        // 自提门店筛选
        if (param.getExtractShopId() != null && param.getExtractShopId() > 0) {
            queryWrapper.eq(Order::getExtractShopId, param.getExtractShopId());
        }

        // 用户ID筛选
        if (param.getUserId() != null && param.getUserId() > 0) {
            queryWrapper.eq(Order::getUserId, param.getUserId());
        }
        
        // 根据订单类型设置状态条件
        setDataTypeCondition(queryWrapper, param.getOrderType());
        
        // 排序：按创建时间倒序
        queryWrapper.orderByDesc(Order::getCreateTime);
        
        return queryWrapper;
    }

    /**
     * 根据订单类型设置状态条件
     */
    private void setDataTypeCondition(LambdaQueryWrapper<Order> queryWrapper, Integer orderType) {
        if (orderType == null) {
            return;
        }
        
        switch (orderType) {
            case StoreOrderListParam.TYPE_DELIVERY:
                // 待发货：已付款，未发货，已审核，订单状态正常
                queryWrapper.and(wrapper -> wrapper
                    .eq(Order::getPayStatus, PayStatusEnum.SUCCESS.getValue())
                    .in(Order::getDeliveryStatus, DeliveryStatusEnum.PENDING.getValue(), DeliveryStatusEnum.PARTIAL.getValue())
                    .eq(Order::getAuditStatus, AuditStatusEnum.APPROVED.getValue())
                    .eq(Order::getOrderStatus, OrderStatusEnum.PROCESSING.getValue())
                );
                break;
                
            case StoreOrderListParam.TYPE_AUDIT:
                // 待审核：订单状态正常，审核状态为初审或复审
                queryWrapper.and(wrapper -> wrapper
                    .in(Order::getOrderStatus, OrderStatusEnum.PROCESSING.getValue(), OrderStatusEnum.PENDING_CANCEL.getValue())
                    .and(innerWrapper -> innerWrapper
                        .eq(Order::getAuditStatus, AuditStatusEnum.FIRST_PENDING.getValue())
                        .or()
                        .eq(Order::getAuditStatus, AuditStatusEnum.PENDING.getValue())
                    )
                );
                break;
                
            case StoreOrderListParam.TYPE_RECEIPT:
                // 待收货：已付款，已发货，已审核，订单状态正常
                queryWrapper.and(wrapper -> wrapper
                    .eq(Order::getPayStatus, PayStatusEnum.SUCCESS.getValue())
                    .eq(Order::getDeliveryStatus, DeliveryStatusEnum.DELIVERED.getValue())
                    .eq(Order::getAuditStatus, AuditStatusEnum.APPROVED.getValue())
                    .eq(Order::getOrderStatus, OrderStatusEnum.PROCESSING.getValue())
                );
                break;
                
            case StoreOrderListParam.TYPE_PAY:
                // 待付款：未付款，订单状态正常
                queryWrapper.and(wrapper -> wrapper
                    .eq(Order::getPayStatus, PayStatusEnum.PENDING.getValue())
                    .eq(Order::getOrderStatus, OrderStatusEnum.PROCESSING.getValue())
                );
                break;
                
            case StoreOrderListParam.TYPE_COMPLETE:
                // 已完成：已收货，订单状态正常
                queryWrapper.and(wrapper -> wrapper
                    .eq(Order::getReceiptStatus, ReceiptStatusEnum.RECEIVED.getValue())
                    .eq(Order::getOrderStatus, OrderStatusEnum.COMPLETED.getValue())
                );
                break;
                
            case StoreOrderListParam.TYPE_CANCEL:
                // 已取消：订单状态为已取消
                queryWrapper.eq(Order::getOrderStatus, OrderStatusEnum.CANCELLED.getValue());
                break;
                
            default:
                // 全部订单：不设置额外条件
                break;
        }
    }

    /**
     * 转换为订单列表VO
     */
    private StoreOrderListVo convertToOrderListVo(Order order) {
        StoreOrderListVo vo = new StoreOrderListVo();
        BeanUtils.copyProperties(order, vo);
        // 设置时间
        vo.setCreateTime(TimeUtil.changeToLocalDateTime(order.getCreateTime()));
        vo.setOrderId(order.getOrderId().longValue());
        // 查询订单商品信息
        List<OrderGoods> orderGoods = storeOrderMapper.selectOrderGoods(order.getOrderId().longValue());
        if (orderGoods != null && !orderGoods.isEmpty()) {
            List<StoreOrderListVo.OrderGoodsVo> goodsList = orderGoods.stream()
                .map(this::convertToOrderGoodsListVo)
                .collect(Collectors.toList());
            vo.setGoods(goodsList);
        }
        
        // 查询用户信息
        User user = userMapper.selectById(order.getUserId().longValue());
        if (user != null) {
            StoreOrderListVo.OrderUserVo userVo = new StoreOrderListVo.OrderUserVo();
            userVo.setUserId(user.getUserId());
            userVo.setNickName(user.getNickName() != null ? user.getNickName() : user.getRealName());
            vo.setUser(userVo);
        }
        
        // 设置支付方式信息
        StoreOrderListVo.PayTypeVo payTypeVo = new StoreOrderListVo.PayTypeVo();
        payTypeVo.setValue(order.getPayType());
        payTypeVo.setText(PayTypeEnum.getNameByValue(order.getPayType()));
        vo.setPayType(payTypeVo);
        
        // 设置配送方式信息
        StoreOrderListVo.DeliveryTypeVo deliveryTypeVo = new StoreOrderListVo.DeliveryTypeVo();
        deliveryTypeVo.setValue(order.getDeliveryType());
        deliveryTypeVo.setText(DeliveryTypeEnum.getNameByValue(order.getDeliveryType()));
        vo.setDeliveryType(deliveryTypeVo);
        
        // 设置付款状态信息
        StoreOrderListVo.OrderStatusVo payStatusVo = new StoreOrderListVo.OrderStatusVo();
        payStatusVo.setValue(order.getPayStatus());
        payStatusVo.setText(PayStatusEnum.getNameByValue(order.getPayStatus()));
        vo.setPayStatus(payStatusVo);
        
        // 设置审核状态信息
        StoreOrderListVo.OrderStatusVo auditStatusVo = new StoreOrderListVo.OrderStatusVo();
        auditStatusVo.setValue(order.getAuditStatus());
        auditStatusVo.setText(AuditStatusEnum.getNameByValue(order.getAuditStatus()));
        vo.setAuditStatus(auditStatusVo);
        
        // 设置发货状态信息
        StoreOrderListVo.OrderStatusVo deliveryStatusVo = new StoreOrderListVo.OrderStatusVo();
        deliveryStatusVo.setValue(order.getDeliveryStatus());
        deliveryStatusVo.setText(DeliveryStatusEnum.getNameByValue(order.getDeliveryStatus()));
        vo.setDeliveryStatus(deliveryStatusVo);
        
        // 设置收货状态信息
        StoreOrderListVo.OrderStatusVo receiptStatusVo = new StoreOrderListVo.OrderStatusVo();
        receiptStatusVo.setValue(order.getReceiptStatus());
        receiptStatusVo.setText(ReceiptStatusEnum.getNameByValue(order.getReceiptStatus()));
        vo.setReceiptStatus(receiptStatusVo);
        
        // 设置订单状态信息
        StoreOrderListVo.OrderStatusVo orderStatusVo = new StoreOrderListVo.OrderStatusVo();
        orderStatusVo.setValue(order.getOrderStatus());
        orderStatusVo.setText(OrderStatusEnum.getNameByValue(order.getOrderStatus()));
        vo.setOrderStatus(orderStatusVo);
        
        return vo;
    }

    /**
     * 转换为订单详情VO
     */
    private StoreOrderDetailVo convertToOrderDetailVo(Order order) {
        StoreOrderDetailVo vo = new StoreOrderDetailVo();
        BeanUtils.copyProperties(order, vo);
        vo.setRemark(order.getBuyerRemark());
        vo.setOrderId(order.getOrderId().longValue());
        // 设置时间
        vo.setCreateTime(TimeUtil.changeToLocalDateTime(order.getCreateTime()));
        if (order.getPayTime() != null) {
            vo.setPayTime(TimeUtil.changeToLocalDateTime(order.getPayTime()));
        }
        if (order.getDeliveryTime() != null) {
            vo.setDeliveryTime(TimeUtil.changeToLocalDateTime(order.getDeliveryTime()));
        }
        if (order.getReceiptTime() != null) {
            vo.setReceiptTime(TimeUtil.changeToLocalDateTime(order.getReceiptTime()));
        }

        // 设置支付方式信息
        StoreOrderDetailVo.PayTypeVo payTypeVo = new StoreOrderDetailVo.PayTypeVo();
        payTypeVo.setValue(order.getPayType());
        payTypeVo.setText(PayTypeEnum.getNameByValue(order.getPayType()));
        vo.setPayType(payTypeVo);

        // 设置配送方式信息
        StoreOrderDetailVo.DeliveryTypeVo deliveryTypeVo = new StoreOrderDetailVo.DeliveryTypeVo();
        deliveryTypeVo.setValue(order.getDeliveryType());
        deliveryTypeVo.setText(DeliveryTypeEnum.getNameByValue(order.getDeliveryType()));
        vo.setDeliveryType(deliveryTypeVo);

        // 设置付款状态信息
        StoreOrderDetailVo.OrderStatusVo payStatusVo = new StoreOrderDetailVo.OrderStatusVo();
        payStatusVo.setValue(order.getPayStatus());
        payStatusVo.setText(PayStatusEnum.getNameByValue(order.getPayStatus()));
        vo.setPayStatus(payStatusVo);

        // 设置审核状态信息
        StoreOrderDetailVo.OrderStatusVo auditStatusVo = new StoreOrderDetailVo.OrderStatusVo();
        auditStatusVo.setValue(order.getAuditStatus());
        auditStatusVo.setText(AuditStatusEnum.getNameByValue(order.getAuditStatus()));
        vo.setAuditStatus(auditStatusVo);

        // 设置发货状态信息
        StoreOrderDetailVo.OrderStatusVo deliveryStatusVo = new StoreOrderDetailVo.OrderStatusVo();
        deliveryStatusVo.setValue(order.getDeliveryStatus());
        deliveryStatusVo.setText(DeliveryStatusEnum.getNameByValue(order.getDeliveryStatus()));
        vo.setDeliveryStatus(deliveryStatusVo);

        // 设置收货状态信息
        StoreOrderDetailVo.OrderStatusVo receiptStatusVo = new StoreOrderDetailVo.OrderStatusVo();
        receiptStatusVo.setValue(order.getReceiptStatus());
        receiptStatusVo.setText(ReceiptStatusEnum.getNameByValue(order.getReceiptStatus()));
        vo.setReceiptStatus(receiptStatusVo);

        // 设置订单状态信息
        StoreOrderDetailVo.OrderStatusVo orderStatusVo = new StoreOrderDetailVo.OrderStatusVo();
        orderStatusVo.setValue(order.getOrderStatus());
        orderStatusVo.setText(OrderStatusEnum.getNameByValue(order.getOrderStatus()));
        vo.setOrderStatus(orderStatusVo);

        return vo;
    }

    /**
     * 解析JSON数组，支持多种格式
     * @param jsonStr JSON字符串
     * @return 字符串列表
     */
    private List<String> parseJsonArray(String jsonStr) throws Exception {
        if (jsonStr == null || jsonStr.trim().isEmpty()) {
            return new ArrayList<>();
        }

        String trimmed = jsonStr.trim();

        // 如果已经是数组格式 ["1","2","3"]
        if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
            try {
                return objectMapper.readValue(trimmed, new TypeReference<List<String>>() {});
            } catch (Exception e) {
                log.warn("标准JSON数组解析失败，尝试其他格式: {}", trimmed);
            }
        }

        // 如果是逗号分隔的字符串 "1,2,3"
        if (!trimmed.startsWith("[") && trimmed.contains(",")) {
            String[] parts = trimmed.split(",");
            List<String> result = new ArrayList<>();
            for (String part : parts) {
                result.add(part.trim());
            }
            return result;
        }

        // 如果是单个值且没有逗号
        if (!trimmed.startsWith("[") && !trimmed.contains(",")) {
            List<String> result = new ArrayList<>();
            result.add(trimmed);
            return result;
        }

        // 最后的尝试：直接用标准JSON解析
        return objectMapper.readValue(trimmed, new TypeReference<List<String>>() {});
    }

    /**
     * 解析JSON对象，支持多种格式
     * @param jsonStr JSON字符串
     * @return 字符串到整数的映射
     */
    private Map<String, Integer> parseJsonObject(String jsonStr) throws Exception {
        if (jsonStr == null || jsonStr.trim().isEmpty()) {
            return new HashMap<>();
        }

        String trimmed = jsonStr.trim();

        // 如果已经是对象格式 {"1":2,"3":4}
        if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
            try {
                return objectMapper.readValue(trimmed, new TypeReference<Map<String, Integer>>() {});
            } catch (Exception e) {
                log.warn("标准JSON对象解析失败，尝试其他格式: {}", trimmed);
            }
        }

        // 如果是其他格式，尝试直接解析
        return objectMapper.readValue(trimmed, new TypeReference<Map<String, Integer>>() {});
    }

    /**
     * 查询指定订单中指定商品的已发货数量
     * @param orderId 订单ID
     * @param goodsId 商品ID
     * @return 已发货数量
     */
    private Integer getDeliveredQuantity(Integer orderId, Integer goodsId) {
        try {
            // 查询该订单的所有物流记录
            List<OrderExpress> orderExpressList = storeOrderMapper.selectOrderExpress(Long.valueOf(orderId));
            if (orderExpressList == null || orderExpressList.isEmpty()) {
                return 0;
            }

            Integer totalDelivered = 0;

            for (OrderExpress express : orderExpressList) {
                if (express.getGoodsId() != null && express.getGoodsNum() != null) {
                    try {
                        log.debug("解析物流记录，orderExpressId: {}, goodsId: {}, goodsNum: {}",
                                express.getOrderExpressId(), express.getGoodsId(), express.getGoodsNum());

                        // 解析商品ID列表
                        List<String> goodsIdList = parseJsonArray(express.getGoodsId());

                        // 解析商品数量映射
                        Map<String, Integer> goodsNumMap = parseJsonObject(express.getGoodsNum());

                        // 查找指定商品的发货数量
                        String targetGoodsId = String.valueOf(goodsId);
                        if (goodsIdList.contains(targetGoodsId) && goodsNumMap.containsKey(targetGoodsId)) {
                            totalDelivered += goodsNumMap.get(targetGoodsId);
                            log.debug("找到商品发货记录，goodsId: {}, quantity: {}", targetGoodsId, goodsNumMap.get(targetGoodsId));
                        }
                    } catch (Exception e) {
                        log.warn("解析物流记录JSON失败，orderExpressId: {}, goodsId: {}, goodsNum: {}, error: {}",
                                express.getOrderExpressId(), express.getGoodsId(), express.getGoodsNum(), e.getMessage());
                    }
                }
            }

            return totalDelivered;
        } catch (Exception e) {
            log.error("查询已发货数量失败，orderId: {}, goodsId: {}", orderId, goodsId, e);
            return 0;
        }
    }

    /**
     * 转换为订单商品详情VO
     */
    private StoreOrderDetailVo.OrderGoodsDetailVo convertToOrderGoodsDetailVo(OrderGoods orderGoods) {
        StoreOrderDetailVo.OrderGoodsDetailVo vo = new StoreOrderDetailVo.OrderGoodsDetailVo();
        BeanUtils.copyProperties(orderGoods, vo);

        // 手动设置BigDecimal字段以确保保留两位小数
        if (orderGoods.getGoodsPrice() != null) {
            vo.setGoodsPrice(orderGoods.getGoodsPrice().setScale(2, RoundingMode.HALF_UP));
        }
        if (orderGoods.getDiscountActivePrice() != null) {
            vo.setDiscountActivePrice(orderGoods.getDiscountActivePrice().setScale(2, RoundingMode.HALF_UP));
        }

        vo.setGoodsId(Long.valueOf(orderGoods.getGoodsId()));
        List<GoodsSku> goodsSkus = goodsSkuMapper.selectByGoodsId(Long.valueOf(orderGoods.getGoodsId()));
        if(goodsSkus != null && goodsSkus.size() > 0) {
            vo.setStockNum(goodsSkus.get(0).getStockNum());
        }
        // 查询该商品的已发货数量
        Integer totalCheckNum = getDeliveredQuantity(orderGoods.getOrderId(), orderGoods.getGoodsId());
        vo.setTotalCheckNum(totalCheckNum);

        // 设置商品图片
        if (orderGoods.getImageId() != null) {
            StoreOrderDetailVo.GoodsImageVo imageVo = new StoreOrderDetailVo.GoodsImageVo();
            List<UploadFile> fileByGoodsId = goodsImageMapper.getFileByGoodsId(Long.valueOf(orderGoods.getImageId()));
            if(fileByGoodsId != null && fileByGoodsId.size() > 0) {
                List<String> collect = fileByGoodsId.stream().map(UploadFile::getFileUrl).collect(Collectors.toList());
                imageVo.setFilePath(collect);
            }
            vo.setImage(imageVo);
        }

        return vo;
    }

    /**
     * 转换为订单地址VO
     */
    private StoreOrderDetailVo.OrderAddressVo convertToOrderAddressVo(OrderAddress orderAddress) {
        StoreOrderDetailVo.OrderAddressVo vo = new StoreOrderDetailVo.OrderAddressVo();
        BeanUtils.copyProperties(orderAddress, vo);

        // 设置地区名称
        if (orderAddress.getRegion() != null) {
            vo.setProvince(orderAddress.getRegion().getProvince());
            vo.setCity(orderAddress.getRegion().getCity());
            vo.setRegion(orderAddress.getRegion().getRegion());
        } else {
            // 如果region为空，尝试通过region ID查询地区名称
            if (orderAddress.getProvinceId() != null) {
                String provinceName = getRegionName(orderAddress.getProvinceId());
                vo.setProvince(provinceName);
            }
            if (orderAddress.getCityId() != null) {
                String cityName = getRegionName(orderAddress.getCityId());
                vo.setCity(cityName);
            }
            if (orderAddress.getRegionId() != null) {
                String regionName = getRegionName(orderAddress.getRegionId());
                vo.setRegion(regionName);
            }
        }

        return vo;
    }

    /**
     * 转换为订单物流VO
     */
    private StoreOrderDetailVo.OrderExpressVo convertToOrderExpressVo(OrderExpress orderExpress) {
        StoreOrderDetailVo.OrderExpressVo vo = new StoreOrderDetailVo.OrderExpressVo();
        BeanUtils.copyProperties(orderExpress, vo);
        // 设置发货时间
        if (orderExpress.getDeliveryTime() != null) {
            vo.setDeliveryTime(TimeUtil.changeToLocalDateTime(orderExpress.getDeliveryTime()));
        }
        
        // 设置物流图片
        if (orderExpress.getImages() != null && !orderExpress.getImages().trim().isEmpty()) {
            try {
                // 解析JSON格式的图片ID数据
                List<String> imageIds = objectMapper.readValue(orderExpress.getImages(),
                    new TypeReference<List<String>>() {});

                // 根据图片ID查询对应的文件信息
                List<String> imageUrls = new ArrayList<>();
                List<String> imageFileNames = new ArrayList<>();

                for (String imageId : imageIds) {
                    try {
                        Long fileId = Long.valueOf(imageId);
                        UploadFile uploadFile = uploadFileMapper.selectById(fileId);
                        if (uploadFile != null) {
                            // 添加图片地址
                            imageUrls.add(uploadFile.getFileUrl());
                            // 添加文件名
                            imageFileNames.add(uploadFile.getFileName());
                        } else {
                            log.warn("未找到图片文件，文件ID: {}", fileId);
                        }
                    } catch (NumberFormatException e) {
                        log.warn("图片ID格式错误: {}", imageId, e);
                    }
                }

                vo.setImages(imageUrls);
                vo.setImagesValue(imageFileNames);

            } catch (Exception e) {
                log.warn("解析物流图片JSON失败，订单物流ID: {}, 图片数据: {}",
                    orderExpress.getOrderExpressId(), orderExpress.getImages(), e);
                // 解析失败时设置空列表
                vo.setImages(new ArrayList<>());
                vo.setImagesValue(new ArrayList<>());
            }
        } else {
            // 如果没有图片数据，设置空列表
            vo.setImages(new ArrayList<>());
            vo.setImagesValue(new ArrayList<>());
        }
        
        return vo;
    }

    /**
     * 转换为自提门店VO
     */
    private StoreOrderDetailVo.ExtractShopVo convertToExtractShopVo(Map<String, Object> shopInfo) {
        StoreOrderDetailVo.ExtractShopVo vo = new StoreOrderDetailVo.ExtractShopVo();
        vo.setShopId(Long.valueOf(shopInfo.get("shop_id").toString()));
        vo.setShopName((String) shopInfo.get("shop_name"));
        vo.setAddress((String) shopInfo.get("address"));
        vo.setPhone((String) shopInfo.get("phone"));
        vo.setBusinessHours((String) shopInfo.get("business_hours"));
        
        return vo;
    }

    /**
     * 转换为订单商品列表VO
     */
    private StoreOrderListVo.OrderGoodsVo convertToOrderGoodsListVo(OrderGoods orderGoods) {
        StoreOrderListVo.OrderGoodsVo vo = new StoreOrderListVo.OrderGoodsVo();
        BeanUtils.copyProperties(orderGoods, vo);

        // 设置商品图片
        if (orderGoods.getImageId() != null) {
            StoreOrderListVo.GoodsImageVo imageVo = new StoreOrderListVo.GoodsImageVo();
            List<UploadFile> fileByGoodsId = goodsImageMapper.getFileByGoodsId(Long.valueOf(orderGoods.getImageId()));
            if(fileByGoodsId != null && fileByGoodsId.size() > 0) {
                List<String> collect = fileByGoodsId.stream().map(UploadFile::getFileUrl).collect(Collectors.toList());
                imageVo.setFilePath(collect);
            }
            vo.setImage(imageVo);
            vo.setGoodsId(Long.valueOf(orderGoods.getGoodsId()));
        }

        return vo;
    }

    /**
     * 转换为订单用户详情VO
     */
    private StoreOrderDetailVo.OrderUserDetailVo convertToOrderUserDetailVo(User user) {
        StoreOrderDetailVo.OrderUserDetailVo vo = new StoreOrderDetailVo.OrderUserDetailVo();
        BeanUtils.copyProperties(user, vo);

        vo.setUserId(user.getUserId());
        vo.setNickName(user.getNickName() != null ? user.getNickName() : user.getRealName());
        vo.setRealName(user.getRealName());

        return vo;
    }

    /**
     * 根据地区ID查询地区名称
     */
    private String getRegionName(Integer regionId) {
        if (regionId == null) {
            return null;
        }
        try {
            Region region = regionMapper.selectById(regionId);
            return region != null ? region.getName() : null;
        } catch (Exception e) {
            log.warn("查询地区名称失败，地区ID: {}", regionId, e);
            return null;
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void express(OrderSendBo bo) {
        try {
        // 基础参数验证
        BizAssertUtil.notNull(bo.getType(), 10001,"发货类型不能为空");
        BizAssertUtil.notEmpty(bo.getImages(), 10002,"发货凭证图片不能为空");
        BizAssertUtil.notNull(bo.getOrderId(), 10003,"订单ID不能为空");

        // 获取订单信息
        Order order = orderService.getById(bo.getOrderId());
        BizAssertUtil.notNull(order, 10004, "订单不存在");

        // 检查订单状态
        if (order.getOrderStatus() != 10) {
            throw new CommonException("订单状态异常，无法发货");
        }

        // 发货验证
        if (bo.getType() == 2) { // 部分发货
            validatePartialDelivery(bo, order);
        }

        // 创建发货记录
        OrderExpress express = insertExpress(bo);

        // 更新订单状态
        updateOrderStatus(bo, express);

        // 发送通知消息
        sendMessage(bo);
        } catch (Exception e) {
          throw new ServiceException( e.getMessage());
        }
    }

    /**
     * 验证全部发货参数
     * @param bo 发货参数
     * @param order 订单信息
     */
    private void validateFullDelivery(OrderSendBo bo, Order order) {
        log.info("开始验证全部发货参数，订单ID: {}", bo.getOrderId());

        // 获取订单商品信息
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(
            new LambdaQueryWrapper<OrderGoods>()
                .eq(OrderGoods::getOrderId, bo.getOrderId())
        );

        // 验证全部发货：检查每个商品的累计发货数量是否超过购买数量
        for (OrderGoods orderGoods : orderGoodsList) {
            Integer goodsId = orderGoods.getGoodsId();
            Integer purchaseNum = orderGoods.getTotalNum();

            // 检查已发货数量
            Integer alreadyDelivered = getAlreadyDeliveredQuantity(bo.getOrderId(), goodsId);
            Integer totalAfterFullDelivery = alreadyDelivered + purchaseNum;

            log.info("全部发货验证 - 商品ID: {}, 购买数量: {}, 已发货: {}, 发货后总量: {}",
                    goodsId, purchaseNum, alreadyDelivered, totalAfterFullDelivery);

            // 验证累计发货数量不能超过购买数量
            if (totalAfterFullDelivery > purchaseNum) {
                log.error("全部发货验证失败 - 超出限制! 商品ID: {}, 购买数量: {}, 发货后总量: {}",
                        goodsId, purchaseNum, totalAfterFullDelivery);
                throw new CommonException("商品[" + orderGoods.getGoodsName() + "]累计发货数量(" + totalAfterFullDelivery +
                        ")不能超过购买数量(" + purchaseNum + ")");
            } else {
                log.info("全部发货验证通过 - 商品ID: {}, 购买数量: {}, 发货后总量: {}", goodsId, purchaseNum, totalAfterFullDelivery);
            }
        }
    }

    /**
     * 验证部分发货参数
     * @param bo 发货参数
     * @param order 订单信息
     */
    private void validatePartialDelivery(OrderSendBo bo, Order order) {

        // 验证商品发货数量参数
        BizAssertUtil.notEmpty(bo.getGoodsNum(), 10005, "部分发货必须指定商品发货数量");

        // 获取订单商品信息
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(
            new LambdaQueryWrapper<OrderGoods>()
                .eq(OrderGoods::getOrderId, bo.getOrderId())
        );

        // 验证发货数量不能超过订单数量
        for (OrderGoods orderGoods : orderGoodsList) {
            Integer goodsId = orderGoods.getGoodsId();

            Integer deliveryNum = bo.getGoodsNum().get(goodsId.longValue());

            if (deliveryNum != null) {
                // 检查发货数量是否合理
                if (deliveryNum <= 0) {
                    throw new CommonException("商品[" + orderGoods.getGoodsName() + "]发货数量必须大于0");
                }

                if (deliveryNum > orderGoods.getTotalNum()) {
                    throw new CommonException("商品[" + orderGoods.getGoodsName() + "]发货数量不能超过订单数量" + orderGoods.getTotalNum());
                }

                // 检查是否已发货过该商品
                Integer alreadyDelivered = getAlreadyDeliveredQuantity(bo.getOrderId(), goodsId);

                Integer totalAfterDelivery = alreadyDelivered + deliveryNum;

                // 严格验证：发货后总量不能超过购买数量
                if (totalAfterDelivery > orderGoods.getTotalNum()) {
                    throw new CommonException("商品[" + orderGoods.getGoodsName() + "]累计发货数量(" + totalAfterDelivery +
                            ")不能超过购买数量(" + orderGoods.getTotalNum() + ")");
                } else {
                    log.info("发货验证通过 - 商品ID: {}, 购买数量: {}, 发货后总量: {}", goodsId, orderGoods.getTotalNum(), totalAfterDelivery);
                }
            }
        }

        // 验证至少有一个商品要发货
        boolean hasGoodsToDeliver = bo.getGoodsNum().values().stream()
            .anyMatch(num -> num != null && num > 0);
        if (!hasGoodsToDeliver) {
            throw new CommonException("至少要发货一个商品");
        }
    }

    /**
     * 获取商品已发货数量
     * @param orderId 订单ID
     * @param goodsId 商品ID
     * @return 已发货数量
     */
    private Integer getAlreadyDeliveredQuantity(Long orderId, Integer goodsId) {
        List<OrderExpress> expressList = orderExpressService.list(
            new LambdaQueryWrapper<OrderExpress>()
                .eq(OrderExpress::getOrderId, orderId.intValue())
        );

        int totalDelivered = 0;
        for (OrderExpress express : expressList) {
            if (express.getGoodsNum() != null) {
                try {
                    Map<String, Integer> goodsNumMap = parseJsonObject(express.getGoodsNum());
                    Integer deliveredNum = goodsNumMap.get(goodsId.toString());
                    if (deliveredNum != null && deliveredNum > 0) {
                        totalDelivered += deliveredNum;
                    }
                } catch (Exception e) {
                    log.warn("解析发货数量JSON失败，orderId: {}, goodsId: {}, goodsNum: {}, error: {}",
                            orderId, goodsId, express.getGoodsNum(), e.getMessage());
                }
            }
        }

        log.info("商品ID {} 的累计已发货数量: {}, 物流记录数: {}", goodsId, totalDelivered, expressList.size());
        return totalDelivered;
    }

    private void sendMessage(OrderSendBo bo) {
        Order order = orderService.getById(bo.getOrderId());
        LocalDateTime createTime = TimeUtil.changeToLocalDateTime(order.getCreateTime());
        StringBuffer messageContent = new StringBuffer();
        String formattedTime = createTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        messageContent.append("您").append(formattedTime);
        if(bo.getType() == 1){
            messageContent.append("下的订单全部已发货订单号[").append(order.getOrderNo()).append("]");
        }else{
            messageContent.append("下的订单部分已发货订单号[").append(order.getOrderNo()).append("]");
        }
        messageContent.append("物流公司[").append(bo.getExpressCompany()).append("],").append("物流单号[").append(bo.getExpressNo()).append("]");
        Message message = new Message();
        message.setMessageContent(messageContent.toString());
        message.setMessageTitle("订单发货通知");
        message.setUserId(order.getUserId());
        message.setIsType(30);
        message.setCreateTime(System.currentTimeMillis() / 1000);
        message.setUpdateTime(System.currentTimeMillis() / 1000);
        messageService.sendMessage(message);
    }

    private void updateOrderStatus(OrderSendBo bo, OrderExpress express) {
        // 更新订单商品状态
        if (bo.getType() == 1) { // 全部发货
            // 全部发货：标记所有商品为已发货
            LambdaUpdateWrapper<OrderGoods> wrapper = new LambdaUpdateWrapper<OrderGoods>()
                    .eq(OrderGoods::getOrderId, bo.getOrderId())
                    .set(OrderGoods::getIsOrderExpress, 20)
                    .set(OrderGoods::getOrderExpressId, express.getOrderExpressId().longValue());
            orderGoodsMapper.update(wrapper);
        } else if (bo.getType() == 2) { // 部分发货
            // 部分发货：只标记本次发货的商品
            if (bo.getGoodsNum() != null && !bo.getGoodsNum().isEmpty()) {
                for (Map.Entry<Long, Integer> entry : bo.getGoodsNum().entrySet()) {
                    Long goodsId = entry.getKey();
                    Integer deliveryNum = entry.getValue();

                    if (deliveryNum != null && deliveryNum > 0) {
                        // 获取该商品的订单信息
                        OrderGoods orderGoods = orderGoodsMapper.selectOne(
                            new LambdaQueryWrapper<OrderGoods>()
                                .eq(OrderGoods::getOrderId, bo.getOrderId())
                                .eq(OrderGoods::getGoodsId, goodsId)
                        );

                        // 计算累计发货数量（包括本次发货）
                        Integer alreadyDelivered = getAlreadyDeliveredQuantity(bo.getOrderId(), goodsId.intValue());
                        Integer totalDelivered = alreadyDelivered;

                        // 检查本次物流记录是否包含此商品，如果包含则不需要重复计算本次发货数量
                        if (express.getGoodsNum() != null) {
                            try {
                                Map<String, Integer> currentExpressGoods = parseJsonObject(express.getGoodsNum());
                                Integer currentDeliveryNum = currentExpressGoods.get(goodsId.toString());
                                if (currentDeliveryNum != null && currentDeliveryNum.equals(deliveryNum)) {
                                } else {
                                    // 如果物流记录中没有此商品或数量不匹配，才需要加上本次发货数量
                                    totalDelivered = alreadyDelivered + deliveryNum;
                                }
                            } catch (Exception e) {
                                totalDelivered = alreadyDelivered + deliveryNum;
                            }
                        } else {
                            totalDelivered = alreadyDelivered + deliveryNum;
                        }

                        // 根据累计发货数量决定状态
                        int expressStatus;
                        if (totalDelivered == orderGoods.getTotalNum()) {
                            // 全部发货完成：这次发货数量 + 已发货数量 = 购买总数量
                            expressStatus = 20; // 全部已发货
                        } else {
                            // 部分发货：这次发货数量 + 已发货数量 < 购买总数量
                            expressStatus = 10; // 部分发货状态
                        }

                        LambdaUpdateWrapper<OrderGoods> wrapper = new LambdaUpdateWrapper<OrderGoods>()
                                .eq(OrderGoods::getOrderId, bo.getOrderId())
                                .eq(OrderGoods::getGoodsId, goodsId)
                                .set(OrderGoods::getIsOrderExpress, expressStatus)
                                .set(OrderGoods::getOrderExpressId, express.getOrderExpressId().longValue());
                        int updateCount = orderGoodsMapper.update(wrapper);
                    }
                }
            }
        }

        // 更新订单发货状态
        LambdaUpdateWrapper<Order> wrapper2 = new LambdaUpdateWrapper<Order>()
                .eq(Order::getOrderId, bo.getOrderId());

        if (bo.getType() == 1) {
            // 全部发货：标记为已发货
            wrapper2.set(Order::getDeliveryStatus, 20);
        } else if (bo.getType() == 2) {
            // 部分发货：检查是否还有未发货的商品
            if (isAllGoodsDelivered(bo.getOrderId())) {
                // 所有商品都已发货，标记为已发货
                wrapper2.set(Order::getDeliveryStatus, 20);
            } else {
                // 还有商品未发货，标记为部分已发货
                wrapper2.set(Order::getDeliveryStatus, 30);
            }
        }

        wrapper2.set(Order::getDeliveryTime, System.currentTimeMillis() / 1000);

        // 设置物流信息
        if (express.getExpressNo() != null && !"".equals(express.getExpressNo())) {
            wrapper2.set(Order::getExpressNo, express.getExpressNo());
        }
        if (express.getExpressCompany() != null && !"".equals(express.getExpressCompany())) {
            wrapper2.set(Order::getExpressCompany, express.getExpressCompany());
        } else {
            if (bo.getExpressCompany() != null && !"".equals(bo.getExpressCompany())) {
                wrapper2.set(Order::getExpressCompany, bo.getExpressCompany());
            }
        }
        if (bo.getExpressNo() != null && !"".equals(bo.getExpressNo())) {
            wrapper2.set(Order::getExpressNo, bo.getExpressNo());
        }

        orderService.update(wrapper2);
    }

    /**
     * 检查订单中的所有商品是否都已全部发货
     * @param orderId 订单ID
     * @return true-全部发货完成，false-还有商品未全部发货
     */
    private boolean isAllGoodsDelivered(Long orderId) {
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(
            new LambdaQueryWrapper<OrderGoods>()
                .eq(OrderGoods::getOrderId, orderId)
        );

        // 检查是否有商品还未全部发货
        for (OrderGoods orderGoods : orderGoodsList) {
            if (orderGoods.getIsOrderExpress() != 20) {
                return false; // 还有商品未全部发货
            }
        }

        return true; // 所有商品都已全部发货
    }

    private OrderExpress insertExpress(OrderSendBo bo) {
        OrderExpress express = new OrderExpress();

        // 获取订单商品信息
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(
            new LambdaQueryWrapper<OrderGoods>().eq(OrderGoods::getOrderId, bo.getOrderId())
        );

        express.setOrderId(bo.getOrderId().intValue());

        if (bo.getType() == 1) { // 全部发货
            // 全部发货逻辑：发货所有商品的全部数量
            String goodsIds = orderGoods.stream()
                    .map(OrderGoods::getGoodsId)
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));

            String goodsIdTotalNumPairs = orderGoods.stream()
                    .map(item -> "\"" + item.getGoodsId() + "\":" + item.getTotalNum())
                    .collect(Collectors.joining(","));

            String goodsInfo = "{" + goodsIdTotalNumPairs + "}";
            express.setGoodsId(goodsIds);
            express.setGoodsNum(goodsInfo);

        } else if (bo.getType() == 2) { // 部分发货
            // 部分发货逻辑：只发货指定商品的指定数量
            BizAssertUtil.notEmpty(bo.getGoodsNum(), 10006, "部分发货必须指定商品发货数量");

            // 构建本次发货的商品ID列表和数量信息
            List<String> goodsIdList = new ArrayList<>();
            List<String> goodsNumPairs = new ArrayList<>();

            for (Map.Entry<Long, Integer> entry : bo.getGoodsNum().entrySet()) {
                Long goodsId = entry.getKey();
                Integer deliveryNum = entry.getValue();

                if (deliveryNum != null && deliveryNum > 0) {
                    goodsIdList.add(goodsId.toString());
                    goodsNumPairs.add("\"" + goodsId + "\":" + deliveryNum);
                }
            }

            if (goodsIdList.isEmpty()) {
                throw new CommonException("没有有效的商品发货信息");
            }

            express.setGoodsId(String.join(",", goodsIdList));
            express.setGoodsNum("{" + String.join(",", goodsNumPairs) + "}");
        }
        express.setExpressCompany("");
        express.setExpressNo("");
        // 设置物流信息
        if (StrUtil.isNotBlank(bo.getExpressCompany())) {
            Express express1 = this.baseMapper.getExpress(bo.getExpressCompany());
            if (express1 != null) {
                express.setExpressId(express1.getExpressId().intValue());
                express.setExpressCompany(express1.getExpressName());
            } else {
                express.setExpressCompany(bo.getExpressCompany());
            }
        }

        // 设置发货凭证图片 - 将逗号分隔的字符串转换为JSON数组格式
        if (StrUtil.isNotBlank(bo.getImages())) {
            try {
                String[] imageArray = bo.getImages().split(",");
                List<String> imageList = Arrays.asList(imageArray);
                String imagesJson = objectMapper.writeValueAsString(imageList);
                express.setImages(imagesJson);
            } catch (Exception e) {
                log.error("发货凭证图片格式转换失败，原始数据: {}", bo.getImages(), e);
                // 如果转换失败，保持原始格式
                express.setImages(bo.getImages());
            }
        } else {
            express.setImages("[]"); // 空数组的JSON格式
        }

        // 设置发货时间
        express.setDeliveryTime(System.currentTimeMillis() / 1000);

        // 设置物流单号
        if (StrUtil.isNotBlank(bo.getExpressNo())) {
            express.setExpressNo(bo.getExpressNo());
        }

        // 设置其他固定字段
        express.setWxappId(10001);
        express.setCreateTime(System.currentTimeMillis() / 1000);
        express.setUpdateTime(System.currentTimeMillis() / 1000);

        // 保存到数据库
        orderExpressService.save(express);
        return express;
    }

    @Override
    public List<Express> getExpressList() {
        try {
            log.info("获取物流公司列表");
            return this.baseMapper.getExpressList();
        } catch (Exception e) {
            log.error("获取物流公司列表失败", e);
            throw new RuntimeException("获取物流公司列表失败：" + e.getMessage());
        }
    }

    /**
     * 批量发货订单信息封装类
     */
    private static class BatchDeliveryOrderInfo {
        private final Order order;
        private final String expressNo;

        public BatchDeliveryOrderInfo(Order order, String expressNo) {
            this.order = order;
            this.expressNo = expressNo;
        }

        public Order getOrder() {
            return order;
        }

        public String getExpressNo() {
            return expressNo;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelivery(MultipartFile file, Long expressId) {
        try {

            // 验证物流公司是否存在
            Express expressCompany = expressService.getById(expressId);
            if (expressCompany == null) {
                throw new CommonException("物流公司不存在：ID=" + expressId);
            }

            // 使用用户现有的EasyExcel读取逻辑
            List<OrderExpressTemplate> templateList = new ArrayList<>();
            try {
                templateList = EasyExcel.read(file.getInputStream())
                        .head(OrderExpressTemplate.class)
                        .sheet()
                        .doReadSync();
            } catch (IOException e) {
                log.error("Excel文件读取失败", e);
                throw new CommonException("Excel文件读取失败：" + e.getMessage());
            }

            if (templateList == null || templateList.isEmpty()) {
                throw new CommonException("Excel文件中没有有效的发货数据");
            }

            if (templateList.size() > 1000) {
                throw new CommonException("单次批量发货不能超过1000个订单");
            }

            // 数据验证和清理
            List<OrderExpressTemplate> validDataList = validateTemplateData(templateList);

            if (validDataList.isEmpty()) {
                throw new CommonException("Excel文件中没有有效的发货数据");
            }

            // 执行批量全部发货
            List<BatchDeliveryOrderInfo> successfulOrderInfos = processBatchFullDelivery(expressId, expressCompany.getExpressName(), validDataList);

            log.info("批量发货处理完成，成功处理{}条数据", validDataList.size());

            // 为成功发货的订单发送消息通知
            sendBatchDeliveryMessages(successfulOrderInfos, expressCompany.getExpressName());

        } catch (Exception e) {
            log.error("批量发货处理失败", e);
            if (e instanceof CommonException) {
                throw e;
            }
            throw new CommonException("批量发货失败：" + e.getMessage());
        }
    }

    /**
     * 为批量发货的订单发送消息通知
     * @param successfulOrderInfos 成功发货的订单信息列表
     * @param expressCompany 物流公司名称
     */
    private void sendBatchDeliveryMessages(List<BatchDeliveryOrderInfo> successfulOrderInfos, String expressCompany) {
        if (successfulOrderInfos == null || successfulOrderInfos.isEmpty()) {
            return;
        }

        log.info("开始为{}个成功发货的订单发送消息通知", successfulOrderInfos.size());

        for (BatchDeliveryOrderInfo orderInfo : successfulOrderInfos) {
            try {
                Order order = orderInfo.getOrder();
                String expressNo = orderInfo.getExpressNo();

                // 获取订单创建时间
                LocalDateTime createTime = TimeUtil.changeToLocalDateTime(order.getCreateTime());
                String formattedTime = createTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

                // 构建消息内容
                StringBuffer messageContent = new StringBuffer();
                messageContent.append("您").append(formattedTime);
                messageContent.append("下的订单全部已发货订单号[").append(order.getOrderNo()).append("]");
                messageContent.append("物流公司[").append(expressCompany).append("],");
                messageContent.append("物流单号[").append(expressNo).append("]");

                // 创建消息对象
                Message message = new Message();
                message.setMessageContent(messageContent.toString());
                message.setMessageTitle("订单发货通知");
                message.setUserId(order.getUserId());
                message.setIsType(30); // 发货通知类型
                message.setCreateTime(System.currentTimeMillis() / 1000);

                // 发送消息
                messageService.sendMessage(message);

                log.debug("为订单[{}]发送发货消息通知成功", order.getOrderNo());
            } catch (Exception e) {
                log.error("为订单[{}]发送发货消息通知失败：{}", orderInfo.getOrder().getOrderNo(), e.getMessage());
                // 不抛出异常，避免影响其他消息的发送
            }
        }

        log.info("批量发货消息通知发送完成，共发送{}条消息", successfulOrderInfos.size());
    }

    /**
     * 验证模板数据
     */
    private List<OrderExpressTemplate> validateTemplateData(List<OrderExpressTemplate> templateList) {
        List<OrderExpressTemplate> validDataList = new ArrayList<>();

        for (int i = 0; i < templateList.size(); i++) {
            OrderExpressTemplate data = templateList.get(i);
            int rowNum = i + 2; // Excel行号从第2行开始（第1行是表头）

            if (data == null) {
                log.warn("第{}行数据为空，跳过", rowNum);
                continue;
            }

            // 清理数据
            data.trimData();

            // 验证数据有效性
            if (!data.isValid()) {
                throw new CommonException("第" + rowNum + "行：订单号和物流单号都不能为空");
            }
//
//            // 检查订单号重复
//            if (!orderNoSet.add(data.getOrderNo())) {
//                throw new CommonException("第" + rowNum + "行：订单号[" + data.getOrderNo() + "]重复");
//            }
//
//            // 检查物流单号重复
//            if (!expressNoSet.add(data.getExpressNo())) {
//                throw new CommonException("第" + rowNum + "行：物流单号[" + data.getExpressNo() + "]重复");
//            }

            validDataList.add(data);
        }

        log.info("数据验证完成，有效数据{}条", validDataList.size());
        return validDataList;
    }

    /**
     * 处理批量全部发货
     * @return 成功发货的订单信息列表，用于发送消息
     */
    private List<BatchDeliveryOrderInfo> processBatchFullDelivery(Long expressId, String expressName, List<OrderExpressTemplate> validDataList) {
        // 获取所有订单号
        List<String> orderNos = validDataList.stream()
                .map(OrderExpressTemplate::getOrderNo)
                .collect(Collectors.toList());

        // 批量查询订单信息
        List<Order> orders = this.list(new LambdaQueryWrapper<Order>()
                .in(Order::getOrderNo, orderNos)
                .eq(Order::getIsDelete, 0));

        // 验证订单
        validateOrdersForBatchDelivery(orders, orderNos);

        // 执行批量发货
        int successCount = 0;
        int failCount = 0;
        List<String> errorMessages = new ArrayList<>();
        List<BatchDeliveryOrderInfo> successfulOrderInfos = new ArrayList<>();

        for (OrderExpressTemplate template : validDataList) {
            try {
                Order order = orders.stream()
                        .filter(o -> o.getOrderNo().equals(template.getOrderNo()))
                        .findFirst()
                        .orElse(null);

                if (order != null) {
                    // 执行全部发货
                    executeFullDelivery(order, expressId, expressName, template.getExpressNo());
                    successCount++;
                    successfulOrderInfos.add(new BatchDeliveryOrderInfo(order, template.getExpressNo())); // 收集成功发货的订单信息
                    log.info("订单[{}]全部发货成功，物流单号：{}", template.getOrderNo(), template.getExpressNo());
                } else {
                    failCount++;
                    errorMessages.add("订单" + template.getOrderNo() + "：订单不存在");
                }
            } catch (Exception e) {
                failCount++;
                errorMessages.add("订单" + template.getOrderNo() + "：" + e.getMessage());
                log.error("订单{}发货失败：{}", template.getOrderNo(), e.getMessage());
            }
        }

        // 记录处理结果
        log.info("批量发货处理完成 - 成功: {}, 失败: {}", successCount, failCount);

        if (!errorMessages.isEmpty()) {
            log.warn("发货失败详情: {}", String.join("; ", errorMessages));
        }

        // 如果全部失败，抛出异常
        if (successCount == 0) {
            throw new CommonException("批量发货完全失败：" + String.join("; ", errorMessages));
        }

        // 如果部分失败，记录警告但不抛出异常
        if (failCount > 0) {
            log.warn("批量发货部分成功，成功{}个，失败{}个", successCount, failCount);
        }

        return successfulOrderInfos;
    }

    /**
     * 验证订单是否可以批量发货
     */
    private void validateOrdersForBatchDelivery(List<Order> orders, List<String> orderNos) {
        // 检查订单是否存在
        List<String> existingOrderNos = orders.stream()
                .map(Order::getOrderNo)
                .collect(Collectors.toList());

        List<String> notFoundOrders = orderNos.stream()
                .filter(orderNo -> !existingOrderNos.contains(orderNo))
                .collect(Collectors.toList());

        if (!notFoundOrders.isEmpty()) {
            throw new CommonException("以下订单不存在：" + String.join(",", notFoundOrders));
        }

        // 检查订单状态
        List<String> invalidOrders = new ArrayList<>();
        for (Order order : orders) {
            if (order.getOrderStatus() != 10) { // 10表示待发货状态
                invalidOrders.add(order.getOrderNo() + "(状态异常)");
            }
            if (order.getPayStatus() != 20) { // 20表示已付款
                invalidOrders.add(order.getOrderNo() + "(未付款)");
            }
            if (order.getDeliveryType() != 10) { // 10表示快递配送
                invalidOrders.add(order.getOrderNo() + "(非快递配送)");
            }
        }

        if (!invalidOrders.isEmpty()) {
            throw new CommonException("以下订单无法发货：" + String.join(",", invalidOrders));
        }
    }

    /**
     * 执行订单全部发货
     */
    private void executeFullDelivery(Order order, Long expressId, String expressName, String expressNo) {
        // 获取订单商品信息
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(
                new LambdaQueryWrapper<OrderGoods>()
                        .eq(OrderGoods::getOrderId, order.getOrderId())
        );

        // 创建物流记录
        OrderExpress expressRecord = new OrderExpress();
        expressRecord.setOrderId(order.getOrderId().intValue());
        expressRecord.setExpressId(expressId.intValue());
        expressRecord.setExpressCompany(expressName);
        expressRecord.setExpressNo(expressNo);
        expressRecord.setDeliveryTime(System.currentTimeMillis() / 1000);
        expressRecord.setWxappId(10001);
        expressRecord.setCreateTime(System.currentTimeMillis() / 1000);
        expressRecord.setUpdateTime(System.currentTimeMillis() / 1000);

        // 设置全部发货的商品信息
        String goodsIds = orderGoods.stream()
                .map(OrderGoods::getGoodsId)
                .map(String::valueOf)
                .collect(Collectors.joining(","));

        String goodsNumJson = orderGoods.stream()
                .map(goods -> "\"" + goods.getGoodsId() + "\":" + goods.getTotalNum())
                .collect(Collectors.joining(","));

        expressRecord.setGoodsId(goodsIds);
        expressRecord.setGoodsNum("{" + goodsNumJson + "}");
        expressRecord.setImages(""); // 可以后续添加发货凭证图片

        // 保存物流记录
        orderExpressService.save(expressRecord);

        // 更新商品发货状态
        for (OrderGoods goods : orderGoods) {
            orderGoodsMapper.update(null, new LambdaUpdateWrapper<OrderGoods>()
                    .set(OrderGoods::getIsOrderExpress, 20)
                    .set(OrderGoods::getOrderExpressId, expressRecord.getOrderExpressId().longValue())
                    .eq(OrderGoods::getGoodsId, goods.getGoodsId())
                    .eq(OrderGoods::getOrderId, order.getOrderId()));
        }

        // 更新订单状态为已发货
        orderService.update(null, new LambdaUpdateWrapper<Order>()
                .set(Order::getDeliveryStatus, 20) // 已发货
                .set(Order::getDeliveryTime, System.currentTimeMillis() / 1000)
                .set(Order::getExpressNo, expressNo)
                .set(Order::getExpressCompany, expressName)
                .eq(Order::getOrderId, order.getOrderId()));
    }
}
